"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Send, Loader2, SendHorizontal, Mail, Tag, UserCheck, Users } from "lucide-react";

import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card";
import { Badge } from "@/shared/components/ui/badge";
import { updateCampaignAction } from "../actions/update-campaign-action";
import { dispatchCampaignAction } from "../actions/dispatch-campaign-action";

import { getCampaignStatusLabel } from "../utils/status-labels";

interface SenderOption {
  id: string;
  name: string;
  fromEmail: string;
}

interface ContactListOption {
  id: string;
  name: string;
  contactCount: number;
}

interface DispatchCampaignCardProps {
  campaign: {
    id: string;
    title: string;
    subject: string;
    senderId: string;
    contactListId: string | null;
    status: string;
  };
  senders: SenderOption[];
  contactLists: ContactListOption[];
}

export function DispatchCampaignCard({ campaign, senders, contactLists }: DispatchCampaignCardProps) {
  const router = useRouter();
  const [title, setTitle] = useState(campaign.title || "");
  const [subject, setSubject] = useState(campaign.subject || "");
  const [senderId, setSenderId] = useState(campaign.senderId || senders[0]?.id || "");
  const [contactListId, setContactListId] = useState(campaign.contactListId || "");
  const [isSending, setIsSending] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);

  useEffect(() => {
    if (senders.length > 0) {
      const exists = senders.some((s) => s.id === senderId);
      if (!exists) {
        setSenderId(senders[0].id);
      }
    }
  }, [senders, senderId]);

  const isDraft = campaign.status === "DRAFT";

  async function handleSend() {
    if (!title.trim()) {
      toast.error("Por favor, informe o título interno da campanha.");
      return;
    }
    if (!subject.trim()) {
      toast.error("Por favor, informe o assunto do e-mail.");
      return;
    }
    if (!contactListId) {
      toast.error("Por favor, selecione a lista de contatos que receberá esta campanha.");
      return;
    }

    setIsSending(true);

    try {
      await updateCampaignAction(campaign.id, { title, subject, senderId, contactListId });
      const result = await dispatchCampaignAction(campaign.id);
      toast.success(`Disparo concluído: ${result.total - result.failed}/${result.total} enviados.`);
      router.refresh();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Erro de conexão durante o disparo.");
    } finally {
      setIsSending(false);
    }
  }

  async function handleUpdateMetadata() {
    setIsUpdating(true);
    try {
      await updateCampaignAction(campaign.id, { title, subject, senderId, contactListId: contactListId || null });
      toast.success("Dados da campanha atualizados com sucesso!");
      router.refresh();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Erro ao conectar com o servidor.");
    } finally {
      setIsUpdating(false);
    }
  }

  return (
    <Card className="border border-zinc-200/80 shadow-xs bg-white rounded-2xl overflow-hidden">
      <CardHeader className="bg-zinc-50/70 border-b border-zinc-100 p-5 sm:p-6 pb-4">
        <div className="flex items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <SendHorizontal className="w-5 h-5 text-[#0F9FDF]" />
            <CardTitle className="text-base font-bold text-zinc-900">
              Configurações &amp; Disparo de E-mail
            </CardTitle>
          </div>
          <Badge variant={isDraft ? "secondary" : "default"} className="text-xs font-bold uppercase">
            {isDraft ? "Pronto para Envio" : getCampaignStatusLabel(campaign.status)}
          </Badge>
        </div>
        <CardDescription className="text-xs text-zinc-500">
          Defina o título interno, o assunto do e-mail, o remetente autorizado e a lista de contatos antes de efetuar o disparo.
        </CardDescription>
      </CardHeader>
      <CardContent className="p-5 sm:p-6 space-y-4">
        {/* Single Column on Mobile, 4 Columns on Desktop */}
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
          <div>
            <Label htmlFor="dispatch-title" className="text-xs font-bold text-zinc-800 mb-1.5 flex items-center gap-1.5">
              <Tag className="w-3.5 h-3.5 text-[#0F9FDF]" />
              Título Interno da Campanha
            </Label>
            <Input
              id="dispatch-title"
              value={title}
              disabled={!isDraft || isSending}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Ex: Lançamento de Verão 2026"
              className="text-xs sm:text-sm h-10 rounded-xl bg-white border-zinc-300 text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2"
            />
          </div>

          <div>
            <Label htmlFor="dispatch-subject" className="text-xs font-bold text-zinc-800 mb-1.5 flex items-center gap-1.5">
              <Mail className="w-3.5 h-3.5 text-[#0F9FDF]" />
              Assunto do E-mail (Inboxing)
            </Label>
            <Input
              id="dispatch-subject"
              value={subject}
              disabled={!isDraft || isSending}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Ex: Não perca a nossa oferta especial..."
              className="text-xs sm:text-sm h-10 rounded-xl bg-white border-zinc-300 text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2"
            />
          </div>

          <div>
            <Label htmlFor="dispatch-sender" className="text-xs font-bold text-zinc-800 mb-1.5 flex items-center gap-1.5">
              <UserCheck className="w-3.5 h-3.5 text-[#0F9FDF]" />
              Remetente Autorizado
            </Label>
            <Select
              value={senderId}
              disabled={!isDraft || isSending}
              onValueChange={(val) => setSenderId(val ?? "")}
            >
              <SelectTrigger id="dispatch-sender" className="text-xs sm:text-sm h-10 w-full rounded-xl bg-white border-zinc-300 text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2">
                <SelectValue placeholder="Selecione um remetente">
                  {(val) => {
                    const found = senders.find((s) => s.id === val);
                    if (found) {
                      return `${found.name} (${found.fromEmail})`;
                    }
                    if (senders.length > 0) {
                      return `${senders[0].name} (${senders[0].fromEmail})`;
                    }
                    return val || "Selecione um remetente";
                  }}
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {senders.map((s) => (
                  <SelectItem key={s.id} value={s.id} className="text-xs">
                    {s.name} ({s.fromEmail})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="dispatch-contact-list" className="text-xs font-bold text-zinc-800 mb-1.5 flex items-center gap-1.5">
              <Users className="w-3.5 h-3.5 text-[#0F9FDF]" />
              Lista de Contatos
            </Label>
            <Select
              value={contactListId}
              disabled={!isDraft || isSending}
              onValueChange={(val) => setContactListId(val ?? "")}
            >
              <SelectTrigger id="dispatch-contact-list" className="text-xs sm:text-sm h-10 w-full rounded-xl bg-white border-zinc-300 text-zinc-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2">
                <SelectValue placeholder="Selecione uma lista">
                  {(val) => {
                    const found = contactLists.find((l) => l.id === val);
                    if (found) {
                      return `${found.name} (${found.contactCount} contatos)`;
                    }
                    return "Selecione uma lista";
                  }}
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {contactLists.length === 0 ? (
                  <div className="px-2 py-1.5 text-xs text-zinc-500">
                    Nenhuma lista cadastrada. Crie uma em Contatos &amp; Higienização.
                  </div>
                ) : (
                  contactLists.map((l) => (
                    <SelectItem key={l.id} value={l.id} className="text-xs">
                      {l.name} ({l.contactCount} contatos)
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="pt-2 flex items-center justify-end gap-3 border-t border-zinc-100">
          {isDraft && (
            <Button
              type="button"
              variant="outline"
              size="sm"
              disabled={isUpdating || isSending}
              onClick={handleUpdateMetadata}
              className="border-zinc-300 text-zinc-700 hover:bg-zinc-100 text-xs font-semibold h-10 px-4 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2"
            >
              {isUpdating ? "Salvando..." : "Salvar Alterações"}
            </Button>
          )}

          <Button
            type="button"
            size="sm"
            disabled={!isDraft || isSending}
            onClick={handleSend}
            className="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold h-10 px-5 rounded-xl shadow-xs transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-600 focus-visible:ring-offset-2 cursor-pointer"
          >
            {isSending ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Disparando E-mails...
              </>
            ) : (
              <>
                <Send className="w-4 h-4 mr-2" />
                Disparar Campanha agora
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
