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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
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 { MusicaAlbum } from "@shared/types";
import { useEffect, useState } from "react";
import { toast } from "sonner";

const NONE = "none";

// Lista fixa para manter consistência entre álbuns (evita "Gospel", "gospel",
// "GOSPEL" como valores diferentes). Inclui a linha cristã ao lado dos
// gêneros seculares mais comuns.
const GENEROS = [
  "Gospel",
  "Louvor e Adoração",
  "Hinos e Corais",
  "Contemporâneo Cristão",
  "Rock Cristão",
  "MPB Cristã",
  "MPB",
  "Sertanejo",
  "Pop",
  "Rock",
  "Samba e Pagode",
  "Forró",
  "Eletrônica",
  "Hip Hop e Rap",
  "Reggae",
  "Clássica",
  "Instrumental",
  "Infantil",
  "Outro",
];

type AlbumForm = {
  titulo: string;
  slug: string;
  descricao: string;
  capa: string;
  anoLancamento: string;
  genero: string;
  artistaId: string;
  status: "rascunho" | "publicado" | "arquivado";
  ativo: boolean;
};

const emptyForm: AlbumForm = {
  titulo: "",
  slug: "",
  descricao: "",
  capa: "",
  anoLancamento: "",
  genero: "",
  artistaId: NONE,
  status: "publicado",
  ativo: true,
};

function toForm(al: MusicaAlbum): AlbumForm {
  return {
    titulo: al.titulo,
    slug: al.slug ?? "",
    descricao: al.descricao ?? "",
    capa: al.capa ?? "",
    anoLancamento: al.anoLancamento != null ? String(al.anoLancamento) : "",
    genero: al.genero ?? "",
    artistaId: al.artistaId != null ? String(al.artistaId) : NONE,
    status: al.status ?? "publicado",
    ativo: al.ativo === 1,
  };
}

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

  const utils = trpc.useUtils();
  const { data, isLoading } = trpc.musica.admin.albuns.listar.useQuery({ page, limit: 20 });
  const artistasQuery = trpc.musica.admin.artistas.listar.useQuery(
    { page: 1, limit: 60 },
    { onError: error => toast.error(`Erro ao carregar artistas: ${error.message}`) }
  );

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

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

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

  const deletarMutation = trpc.musica.admin.albuns.deletar.useMutation({
    onSuccess: () => {
      toast.success("Álbum 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 = (al: MusicaAlbum) => {
    setEditing(al);
    setForm(toForm(al));
    setDialogOpen(true);
  };

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

    const payload = {
      titulo: form.titulo.trim(),
      slug: form.slug.trim() || undefined,
      descricao: form.descricao.trim() || null,
      capa: form.capa.trim() || null,
      anoLancamento: form.anoLancamento ? Number(form.anoLancamento) : null,
      genero: form.genero.trim() || null,
      artistaId: form.artistaId === NONE ? null : Number(form.artistaId),
      status: form.status,
      ativo: form.ativo ? 1 : 0,
    };

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

  const handleDelete = (al: MusicaAlbum) => {
    if (!window.confirm(`Excluir o álbum "${al.titulo}"? Faixas associadas ficarão sem álbum.`)) return;
    deletarMutation.mutate({ id: al.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">Álbuns</h1>
            <p className="text-sm text-sof-text-3 mt-1">{data?.total ?? 0} álbum(ns) cadastrado(s)</p>
          </div>
          <Button onClick={openNew} className="bg-sof-gold text-sof-borgonha hover:bg-sof-gold-light font-bold">
            + Novo Álbum
          </Button>
        </div>

        {isLoading ? (
          <p className="text-sof-text-3">Carregando...</p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow className="border-sof-border">
                <TableHead className="text-sof-text-3">Título</TableHead>
                <TableHead className="text-sof-text-3">Artista</TableHead>
                <TableHead className="text-sof-text-3">Status</TableHead>
                <TableHead className="text-sof-text-3">Ativo</TableHead>
                <TableHead className="text-sof-text-3 text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data?.albuns.length ? (
                data.albuns.map(al => (
                  <TableRow key={al.id} className="border-sof-border hover:bg-sof-surface">
                    <TableCell className="text-sof-text font-medium max-w-xs truncate">{al.titulo}</TableCell>
                    <TableCell className="text-sof-text-3 text-sm">
                      {artistasQuery.data?.artistas.find(a => a.id === al.artistaId)?.nome ?? "—"}
                    </TableCell>
                    <TableCell className="text-sof-text-3 text-sm capitalize">{al.status}</TableCell>
                    <TableCell className="text-sof-text-3">{al.ativo === 1 ? "✓" : "✗"}</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(al)}
                      >
                        Editar
                      </Button>
                      <Button size="sm" variant="destructive" onClick={() => handleDelete(al)}>
                        Excluir
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-sof-text-3">
                    Nenhum álbum 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-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editing ? "Editar álbum" : "Novo álbum"}</DialogTitle>
            </DialogHeader>

            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2 space-y-2">
                  <Label>Título *</Label>
                  <Input required value={form.titulo} onChange={e => setForm(f => ({ ...f, titulo: 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>

                <div className="space-y-2">
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={v => setForm(f => ({ ...f, status: v as AlbumForm["status"] }))}>
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="publicado">Publicado</SelectItem>
                      <SelectItem value="rascunho">Rascunho</SelectItem>
                      <SelectItem value="arquivado">Arquivado</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="col-span-2 space-y-2">
                  <Label>Descrição</Label>
                  <Textarea rows={3} value={form.descricao} onChange={e => setForm(f => ({ ...f, descricao: e.target.value }))} />
                </div>

                <div className="col-span-2">
                  <FileUploadField
                    label="Capa"
                    type="image"
                    value={form.capa}
                    onChange={url => setForm(f => ({ ...f, capa: url }))}
                  />
                </div>

                <div className="space-y-2">
                  <Label>Artista</Label>
                  <Select value={form.artistaId} onValueChange={v => setForm(f => ({ ...f, artistaId: v }))}>
                    <SelectTrigger className="w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={NONE}>Nenhum</SelectItem>
                      {artistasQuery.data?.artistas.map(a => (
                        <SelectItem key={a.id} value={String(a.id)}>
                          {a.nome}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label>Ano de lançamento</Label>
                  <Input
                    type="number"
                    value={form.anoLancamento}
                    onChange={e => setForm(f => ({ ...f, anoLancamento: e.target.value }))}
                  />
                </div>

                <div className="space-y-2">
                  <Label>Gênero</Label>
                  <Select value={form.genero || NONE} onValueChange={v => setForm(f => ({ ...f, genero: v === NONE ? "" : v }))}>
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="Selecione um gênero" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={NONE}>Nenhum</SelectItem>
                      {GENEROS.map(g => (
                        <SelectItem key={g} value={g}>
                          {g}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

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

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setDialogOpen(false)}
                  className="border-sof-border text-sof-text hover:bg-sof-surface"
                >
                  Cancelar
                </Button>
                <Button
                  onClick={handleSubmit}
                  disabled={isSaving}
                  className="bg-sof-gold text-sof-borgonha hover:bg-sof-gold-light font-bold"
                >
                  {isSaving ? "Salvando..." : "Salvar"}
                </Button>
              </DialogFooter>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </AdminLayout>
  );
}
