"use client";

import { useState, useEffect, useCallback } from "react";
import { toast } from "sonner";
import { Mail, Server, Trash2, SquarePen, CheckCircle2, AlertTriangle } from "lucide-react";

import { Button } from "@/shared/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card";
import { Badge } from "@/shared/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/shared/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from "@/shared/components/ui/alert-dialog";

import { useSendersStore, type SenderItem } from "../hooks/use-senders-store";
import { getSendersByUserAction } from "../actions/get-senders-by-user-action";
import { createSenderAction } from "../actions/create-sender-action";
import { updateSenderAction } from "../actions/update-sender-action";
import { deleteSenderAction } from "../actions/delete-sender-action";
import { SenderForm, type SenderFormSubmitValues, type VerifiedDomainOption } from "../components/sender-form";
import { getDomainsByUserAction } from "@/modules/domains/actions/get-domains-by-user-action";

export function SenderSettingsView() {
  const { senders, addSender, updateSenderItem, removeSender, setSenders } = useSendersStore();

  const [isLoading, setIsLoading] = useState(true);
  const [loadError, setLoadError] = useState(false);
  const [verifiedDomains, setVerifiedDomains] = useState<VerifiedDomainOption[]>([]);

  const [isAddSenderOpen, setIsAddSenderOpen] = useState(false);
  const [editingSender, setEditingSender] = useState<SenderItem | null>(null);
  const [deletingSender, setDeletingSender] = useState<SenderItem | null>(null);

  const [isSubmittingSender, setIsSubmittingSender] = useState(false);
  const [isDeletingSender, setIsDeletingSender] = useState(false);

  const loadSenders = useCallback(() => {
    setIsLoading(true);
    setLoadError(false);
    getSendersByUserAction()
      .then(({ senders }) => {
        setSenders(senders);
      })
      .catch(() => setLoadError(true))
      .finally(() => setIsLoading(false));
  }, [setSenders]);

  useEffect(() => {
    loadSenders();
    getDomainsByUserAction()
      .then(({ domains }) => {
        setVerifiedDomains(
          domains.filter((d) => d.verificationStatus === "VERIFIED").map((d) => ({ id: d.id, domain: d.domain }))
        );
      })
      .catch(() => {});
  }, [loadSenders]);

  async function handleCreateSender(values: SenderFormSubmitValues) {
    setIsSubmittingSender(true);
    try {
      const created = await createSenderAction(values);
      addSender(created);
      toast.success("Novo remetente cadastrado com sucesso!");
      setIsAddSenderOpen(false);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Não foi possível salvar o remetente.");
    } finally {
      setIsSubmittingSender(false);
    }
  }

  async function handleUpdateSender(values: SenderFormSubmitValues) {
    if (!editingSender) return;

    setIsSubmittingSender(true);
    try {
      const updated = await updateSenderAction(editingSender.id, values);
      updateSenderItem(updated);
      toast.success("Remetente atualizado com sucesso!");
      setEditingSender(null);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Não foi possível atualizar o remetente.");
    } finally {
      setIsSubmittingSender(false);
    }
  }

  async function handleConfirmDelete() {
    if (!deletingSender) return;

    setIsDeletingSender(true);
    try {
      await deleteSenderAction(deletingSender.id);
      removeSender(deletingSender.id);
      toast.success(`Remetente "${deletingSender.name}" removido com sucesso!`);
      setDeletingSender(null);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Não foi possível remover o remetente.");
    } finally {
      setIsDeletingSender(false);
    }
  }

  return (
    <div className="space-y-6">
      {/* Header Bar */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-zinc-200/80">
        <div>
          <div className="flex items-center gap-3">
            <h2 className="text-xs font-bold uppercase tracking-wider text-zinc-700">
              Contas de E-mail Ativas
            </h2>
            <Badge variant="outline" className="border-zinc-300 bg-zinc-100 text-zinc-800 text-xs font-semibold px-2.5 py-0.5">
              {senders.length} {senders.length === 1 ? "configurado" : "configurados"}
            </Badge>
          </div>
          <p className="text-xs sm:text-sm text-zinc-600 mt-1">
            Gerencie as credenciais SMTP autorizadas para envio de newsletters.
          </p>
        </div>

        <Button
          onClick={() => setIsAddSenderOpen(true)}
          className="bg-[#0F9FDF] hover:bg-[#0C87BD] text-white text-xs font-bold h-10 px-4 min-h-[40px] rounded-xl shadow-xs transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2 flex items-center justify-center gap-2 self-start sm:self-auto shrink-0"
        >
          <Mail className="w-4 h-4 shrink-0" aria-hidden="true" />
          <span>Novo Remetente</span>
        </Button>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
          {[0, 1, 2, 3].map((i) => (
            <Card
              key={i}
              className="bg-white border border-zinc-200 shadow-xs rounded-2xl p-4 space-y-3 animate-pulse"
            >
              <div className="flex items-center justify-between gap-2">
                <div className="h-9 w-9 rounded-xl bg-zinc-100" />
                <div className="h-5 w-20 rounded-full bg-zinc-100" />
              </div>
              <div className="space-y-1.5">
                <div className="h-4 w-2/3 rounded bg-zinc-100" />
                <div className="h-3 w-1/2 rounded bg-zinc-100" />
              </div>
              <div className="space-y-2 border-t border-zinc-100 pt-3">
                <div className="h-3 w-full rounded bg-zinc-100" />
                <div className="h-3 w-full rounded bg-zinc-100" />
                <div className="h-3 w-full rounded bg-zinc-100" />
              </div>
            </Card>
          ))}
        </div>
      ) : loadError ? (
        <Card className="bg-white border border-zinc-200 text-left p-6 sm:p-8 rounded-2xl shadow-xs">
          <CardContent className="p-0 space-y-4 max-w-xl">
            <div className="p-3 bg-rose-50 border border-rose-100 rounded-xl text-rose-700 inline-block">
              <AlertTriangle className="w-6 h-6" aria-hidden="true" />
            </div>
            <div>
              <h3 className="text-base font-bold text-zinc-900">Não foi possível carregar os remetentes</h3>
              <p className="text-xs sm:text-sm text-zinc-600 mt-1 leading-relaxed">
                Ocorreu um erro ao buscar suas contas de e-mail configuradas. Tente novamente.
              </p>
            </div>
            <div className="pt-2">
              <Button
                onClick={loadSenders}
                variant="outline"
                className="border-zinc-300 text-zinc-700 hover:bg-zinc-100 text-xs font-semibold h-10 px-5 min-h-[40px] rounded-xl"
              >
                Tentar novamente
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : senders.length === 0 ? (
        <Card className="bg-white border border-zinc-200 text-left p-6 sm:p-8 rounded-2xl shadow-xs">
          <CardContent className="p-0 space-y-4 max-w-xl">
            <div className="p-3 bg-[#E7F6FD] border border-[#0F9FDF]/20 rounded-xl text-[#0F9FDF] inline-block">
              <Mail className="w-6 h-6" aria-hidden="true" />
            </div>
            <div>
              <h3 className="text-base font-bold text-zinc-900">
                Nenhum remetente configurado ainda
              </h3>
              <p className="text-xs sm:text-sm text-zinc-600 mt-1 leading-relaxed">
                Adicione uma conta de e-mail SMTP para realizar o envio seguro de suas campanhas de e-mail com alta entregabilidade.
              </p>
            </div>
            <div className="pt-2">
              <Button
                onClick={() => setIsAddSenderOpen(true)}
                className="bg-[#0F9FDF] hover:bg-[#0C87BD] text-white text-xs font-bold h-10 px-5 min-h-[40px] rounded-xl shadow-xs transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2"
              >
                Adicionar Remetente
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : (
        /* 4 por linha no desktop (xl:grid-cols-4), 2 no tablet (sm:grid-cols-2), 1 no mobile (grid-cols-1) */
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
          {senders.map((s) => (
            <Card
              key={s.id}
              className="bg-white border border-zinc-200/80 hover:border-[#0F9FDF]/50 transition-all shadow-xs rounded-2xl p-4 space-y-3 min-w-0"
            >
              <CardHeader className="p-0 space-y-2">
                <div className="flex items-center justify-between gap-1.5">
                  <div className="p-2 rounded-xl bg-[#E7F6FD] text-[#0F9FDF] border border-[#0F9FDF]/20 shrink-0">
                    <Server className="w-4 h-4 text-[#0F9FDF]" aria-hidden="true" />
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <Badge className="bg-emerald-50 text-emerald-800 border border-emerald-200 text-[10px] font-bold px-2 py-0.5 flex items-center gap-1">
                      <CheckCircle2 className="w-3 h-3 text-emerald-600" aria-hidden="true" />
                      <span>Ativo</span>
                    </Badge>
                    <button
                      type="button"
                      onClick={() => setEditingSender(s)}
                      className="p-1.5 rounded-lg text-zinc-500 hover:text-[#0F9FDF] hover:bg-[#E7F6FD] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2 flex items-center justify-center cursor-pointer"
                      title={`Editar remetente ${s.name}`}
                      aria-label={`Editar remetente ${s.name}`}
                    >
                      <SquarePen className="w-3.5 h-3.5" />
                    </button>
                    <button
                      type="button"
                      onClick={() => setDeletingSender(s)}
                      className="p-1.5 rounded-lg text-zinc-500 hover:text-rose-600 hover:bg-rose-50 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#0F9FDF] focus-visible:ring-offset-2 flex items-center justify-center cursor-pointer"
                      title={`Excluir remetente ${s.name}`}
                      aria-label={`Excluir remetente ${s.name}`}
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
                <div className="min-w-0">
                  <CardTitle
                    className="text-sm font-bold text-zinc-900 leading-snug truncate"
                    title={s.name}
                  >
                    {s.name}
                  </CardTitle>
                  <CardDescription
                    className="text-xs text-[#0F9FDF] font-semibold mt-0.5 truncate block"
                    title={s.fromEmail}
                  >
                    {s.fromEmail}
                  </CardDescription>
                </div>
              </CardHeader>

              <CardContent className="p-0 text-xs space-y-1.5 border-t border-zinc-100 pt-2.5 text-zinc-600">
                {s.provider === "SES" ? (
                  <div className="flex justify-between items-center gap-2">
                    <span className="text-zinc-500 font-medium shrink-0">Domínio SES:</span>
                    <span
                      className="text-zinc-900 font-mono font-semibold text-[11px] text-right truncate"
                      title={s.domain?.domain ?? ""}
                    >
                      {s.domain?.domain ?? "—"}
                    </span>
                  </div>
                ) : (
                  <>
                    <div className="flex justify-between items-center gap-2">
                      <span className="text-zinc-500 font-medium shrink-0">SMTP:</span>
                      <span
                        className="text-zinc-900 font-mono font-semibold text-[11px] text-right truncate"
                        title={s.smtpHost ?? ""}
                      >
                        {s.smtpHost}
                      </span>
                    </div>
                    <div className="flex justify-between items-center gap-2">
                      <span className="text-zinc-500 font-medium shrink-0">Porta:</span>
                      <span className="text-zinc-900 font-mono font-semibold text-[11px]">{s.smtpPort}</span>
                    </div>
                    <div className="flex justify-between items-center gap-2">
                      <span className="text-zinc-500 font-medium shrink-0">Usuário:</span>
                      <span
                        className="text-zinc-900 font-mono font-semibold text-[11px] text-right truncate"
                        title={s.smtpUser ?? ""}
                      >
                        {s.smtpUser}
                      </span>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Create Sender Modal */}
      <Dialog open={isAddSenderOpen} onOpenChange={setIsAddSenderOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Mail className="w-5 h-5 text-[#0F9FDF]" aria-hidden="true" />
              <span>Novo Remetente SMTP</span>
            </DialogTitle>
            <DialogDescription>
              Configure as informações da sua conta de e-mail autorizada para o envio de mensagens.
            </DialogDescription>
          </DialogHeader>

          <SenderForm
            mode="create"
            verifiedDomains={verifiedDomains}
            isSubmitting={isSubmittingSender}
            onCancel={() => setIsAddSenderOpen(false)}
            onSubmit={handleCreateSender}
          />
        </DialogContent>
      </Dialog>

      {/* Edit Sender Modal */}
      <Dialog open={!!editingSender} onOpenChange={(open) => !open && setEditingSender(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <SquarePen className="w-5 h-5 text-[#0F9FDF]" aria-hidden="true" />
              <span>Editar Remetente</span>
            </DialogTitle>
            <DialogDescription>
              Atualize as informações do remetente. Deixe a senha em branco para mantê-la inalterada.
            </DialogDescription>
          </DialogHeader>

          {editingSender && (
            <SenderForm
              mode="edit"
              verifiedDomains={verifiedDomains}
              initialValues={{
                name: editingSender.name,
                fromEmail: editingSender.fromEmail,
                provider: editingSender.provider,
                smtpHost: editingSender.smtpHost ?? "",
                smtpPort: String(editingSender.smtpPort ?? 587),
                smtpUser: editingSender.smtpUser ?? "",
                smtpPass: "",
                domainId: editingSender.domainId ?? "",
              }}
              isSubmitting={isSubmittingSender}
              onCancel={() => setEditingSender(null)}
              onSubmit={handleUpdateSender}
            />
          )}
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <AlertDialog open={!!deletingSender} onOpenChange={(open) => !open && setDeletingSender(null)}>
        <AlertDialogContent className="max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-rose-600">
              Excluir remetente?
            </AlertDialogTitle>
            <AlertDialogDescription>
              Tem certeza que deseja remover o remetente &quot;{deletingSender?.name}&quot;? Esta ação não pode ser desfeita.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>
              Cancelar
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              disabled={isDeletingSender}
              variant="destructive"
            >
              {isDeletingSender ? "Excluindo..." : "Excluir Remetente"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
