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 { MusicaArtista } from "@shared/types";
import { useEffect, useState } from "react";
import { toast } from "sonner";

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

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

function toForm(a: MusicaArtista): ArtistaForm {
  return {
    nome: a.nome,
    slug: a.slug ?? "",
    bio: a.bio ?? "",
    foto: a.foto ?? "",
    ativo: a.ativo === 1,
  };
}

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

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

  const invalidate = () => {
    utils.musica.admin.artistas.listar.invalidate();
  };

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

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

  const deletarMutation = trpc.musica.admin.artistas.deletar.useMutation({
    onSuccess: () => {
      toast.success("Artista 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 = (a: MusicaArtista) => {
    setEditing(a);
    setForm(toForm(a));
    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 = (a: MusicaArtista) => {
    if (!window.confirm(`Excluir o artista "${a.nome}"? Álbuns e faixas associados ficarão sem artista.`)) return;
    deletarMutation.mutate({ id: a.id });
  };

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

  return (
    <AdminLayout>
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold font-display text-sof-gold">Artistas</h1>
            <p className="text-sm text-sof-text-3 mt-1">{data?.total ?? 0} artista(s) cadastrado(s)</p>
          </div>
          <Button onClick={openNew} className="bg-sof-gold text-sof-borgonha hover:bg-sof-gold-light font-bold">
            + Novo Artista
          </Button>
        </div>

        {isLoading ? (
          <p className="text-sof-text-3">Carregando...</p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow className="border-sof-border">
                <TableHead className="text-sof-text-3">Nome</TableHead>
                <TableHead className="text-sof-text-3">Reproduções</TableHead>
                <TableHead className="text-sof-text-3">Ativo</TableHead>
                <TableHead className="text-sof-text-3 text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data?.artistas.length ? (
                data.artistas.map(a => (
                  <TableRow key={a.id} className="border-sof-border hover:bg-sof-surface">
                    <TableCell className="text-sof-text font-medium">{a.nome}</TableCell>
                    <TableCell className="text-sof-text-3">{(a.reproducoes ?? 0).toLocaleString("pt-BR")}</TableCell>
                    <TableCell className="text-sof-text-3">{a.ativo ? "✓" : "✗"}</TableCell>
                    <TableCell className="text-right space-x-2">
                      <Button
                        size="sm"
                        variant="outline"
                        className="border-sof-border text-sof-text hover:bg-sof-surface"
                        onClick={() => openEdit(a)}
                      >
                        Editar
                      </Button>
                      <Button size="sm" variant="destructive" onClick={() => handleDelete(a)}>
                        Excluir
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={4} className="text-center text-sof-text-3">
                    Nenhum artista 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)}
              className="border-sof-border text-sof-text hover:bg-sof-surface"
            >
              ← 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)}
              className="border-sof-border text-sof-text hover:bg-sof-surface"
            >
              Próxima →
            </Button>
          </div>
        )}

        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editing ? "Editar artista" : "Novo artista"}</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)}
                  className="border-sof-border text-sof-text hover:bg-sof-surface"
                >
                  Cancelar
                </Button>
                <Button
                  type="submit"
                  disabled={isSaving}
                  className="bg-sof-gold text-sof-borgonha hover:bg-sof-gold-light font-bold"
                >
                  {isSaving ? "Salvando..." : "Salvar"}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>
    </AdminLayout>
  );
}