import AdminLayout from "@/components/AdminLayout";
import FileUploadField from "@/components/admin/FileUploadField";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { trpc } from "@/lib/trpc";
import type { PodcastApresentador } from "@shared/types";
import { useEffect, useState } from "react";
import { toast } from "sonner";

type ApresentadorForm = {
  nome: string;
  slug: string;
  bio: string;
  foto: string;
  ativo: boolean;
};

const emptyForm: ApresentadorForm = {
  nome: "",
  slug: "",
  bio: "",
  foto: "",
  ativo: true,
};

function toForm(ap: PodcastApresentador): ApresentadorForm {
  return {
    nome: ap.nome,
    slug: ap.slug ?? "",
    bio: ap.bio ?? "",
    foto: ap.foto ?? "",
    ativo: ap.ativo === 1,
  };
}

export default function AdminApresentadores() {
  const [page, setPage] = useState(1);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<PodcastApresentador | null>(null);
  const [form, setForm] = useState<ApresentadorForm>(emptyForm);

  const utils = trpc.useUtils();
  const { data, isLoading } = trpc.podcast.admin.apresentadores.listar.useQuery({ page, limit: 20 });

  const invalidate = () => {
    utils.podcast.admin.apresentadores.listar.invalidate();
    utils.podcast.admin.stats.invalidate();
    utils.podcast.getApresentadores.invalidate();
  };

  const criarMutation = trpc.podcast.admin.apresentadores.criar.useMutation({
    onSuccess: () => {
      toast.success("Apresentador criado.");
      invalidate();
      setDialogOpen(false);
    },
    onError: error => toast.error(error.message),
  });

  const atualizarMutation = trpc.podcast.admin.apresentadores.atualizar.useMutation({
    onSuccess: () => {
      toast.success("Apresentador atualizado.");
      invalidate();
      setDialogOpen(false);
    },
    onError: error => toast.error(error.message),
  });

  const deletarMutation = trpc.podcast.admin.apresentadores.deletar.useMutation({
    onSuccess: () => {
      toast.success("Apresentador removido.");
      invalidate();
    },
    onError: error => toast.error(error.message),
  });

  useEffect(() => {
    if (dialogOpen) return;
    setEditing(null);
    setForm(emptyForm);
  }, [dialogOpen]);

  const openNew = () => {
    setEditing(null);
    setForm(emptyForm);
    setDialogOpen(true);
  };

  const openEdit = (ap: PodcastApresentador) => {
    setEditing(ap);
    setForm(toForm(ap));
    setDialogOpen(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const payload = {
      nome: form.nome.trim(),
      slug: form.slug.trim() || undefined,
      bio: form.bio.trim() || null,
      foto: form.foto.trim() || null,
      ativo: form.ativo ? 1 : 0,
    };

    if (editing) {
      atualizarMutation.mutate({ id: editing.id, ...payload });
    } else {
      criarMutation.mutate(payload);
    }
  };

  const handleDelete = (ap: PodcastApresentador) => {
    if (!window.confirm(`Excluir o apresentador "${ap.nome}"? Episódios associados ficarão sem apresentador.`)) return;
    deletarMutation.mutate({ id: ap.id });
  };

  const isSaving = criarMutation.isPending || atualizarMutation.isPending;

  return (
    <AdminLayout>
      <div className="flex justify-between items-center mb-6">
        <p className="text-sm text-sof-text-3">{data?.total ?? 0} apresentador(es) cadastrado(s)</p>
        <Button onClick={openNew} className="bg-sof-borgonha hover:bg-sof-borgonha-dark text-white">
          + Novo Apresentador
        </Button>
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Nome</TableHead>
            <TableHead>Reproduções</TableHead>
            <TableHead>Ativo</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {isLoading ? (
            <TableRow>
              <TableCell colSpan={4} className="text-center text-sof-text-3">
                Carregando...
              </TableCell>
            </TableRow>
          ) : data?.apresentadores.length ? (
            data.apresentadores.map(ap => (
              <TableRow key={ap.id}>
                <TableCell className="font-medium">{ap.nome}</TableCell>
                <TableCell>{(ap.reproducoes ?? 0).toLocaleString("pt-BR")}</TableCell>
                <TableCell>{ap.ativo ? "Sim" : "Não"}</TableCell>
                <TableCell className="text-right space-x-2">
                  <Button size="sm" variant="outline" onClick={() => openEdit(ap)}>
                    Editar
                  </Button>
                  <Button size="sm" variant="destructive" onClick={() => handleDelete(ap)}>
                    Excluir
                  </Button>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={4} className="text-center text-sof-text-3">
                Nenhum apresentador cadastrado.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>

      {!!data && data.pages > 1 && (
        <div className="flex items-center justify-center gap-4 mt-6">
          <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>
            ← Anterior
          </Button>
          <span className="text-sm text-sof-text-3">
            Página {data.page} de {data.pages}
          </span>
          <Button variant="outline" size="sm" disabled={page >= data.pages} onClick={() => setPage(p => p + 1)}>
            Próxima →
          </Button>
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? "Editar apresentador" : "Novo apresentador"}</DialogTitle>
          </DialogHeader>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label>Nome *</Label>
              <Input required value={form.nome} onChange={e => setForm(f => ({ ...f, nome: e.target.value }))} />
            </div>

            <div className="space-y-2">
              <Label>Slug</Label>
              <Input
                value={form.slug}
                onChange={e => setForm(f => ({ ...f, slug: e.target.value }))}
                placeholder="gerado automaticamente se vazio"
              />
            </div>

            <FileUploadField
              label="Foto"
              type="image"
              value={form.foto}
              onChange={url => setForm(f => ({ ...f, foto: url }))}
            />

            <div className="space-y-2">
              <Label>Bio</Label>
              <Textarea rows={4} value={form.bio} onChange={e => setForm(f => ({ ...f, bio: e.target.value }))} />
            </div>

            <div className="flex items-center gap-3">
              <Switch checked={form.ativo} onCheckedChange={checked => setForm(f => ({ ...f, ativo: checked }))} />
              <Label>Ativo (visível no site)</Label>
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>
                Cancelar
              </Button>
              <Button type="submit" disabled={isSaving} className="bg-sof-borgonha hover:bg-sof-borgonha-dark text-white">
                {isSaving ? "Salvando..." : "Salvar"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </AdminLayout>
  );
}
