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

type VinhetaCategoria = "abertura" | "transicao" | "encerramento";

type VinhetaForm = {
  titulo: string;
  arquivo: string;
  categoria: VinhetaCategoria;
  ativo: boolean;
};

const emptyForm: VinhetaForm = {
  titulo: "",
  arquivo: "",
  categoria: "transicao",
  ativo: true,
};

const categoriaLabels: Record<VinhetaCategoria, string> = {
  abertura: "Abertura",
  transicao: "Transição (AutoDJ)",
  encerramento: "Encerramento",
};

function toForm(v: PodcastVinheta): VinhetaForm {
  return {
    titulo: v.titulo,
    arquivo: v.arquivo,
    categoria: (v.categoria ?? "transicao") as VinhetaCategoria,
    ativo: v.ativo === 1,
  };
}

export default function AdminVinhetas() {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<PodcastVinheta | null>(null);
  const [form, setForm] = useState<VinhetaForm>(emptyForm);

  const utils = trpc.useUtils();
  const { data, isLoading } = trpc.podcast.admin.vinhetas.listar.useQuery();

  const invalidate = () => {
    utils.podcast.admin.vinhetas.listar.invalidate();
    utils.podcast.getVinhetas.invalidate();
  };

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

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

  const deletarMutation = trpc.podcast.admin.vinhetas.deletar.useMutation({
    onSuccess: () => {
      toast.success("Vinheta removida.");
      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 = (v: PodcastVinheta) => {
    setEditing(v);
    setForm(toForm(v));
    setDialogOpen(true);
  };

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

    if (!form.arquivo.trim()) {
      toast.error("Envie ou informe o arquivo de áudio da vinheta.");
      return;
    }

    const payload = {
      titulo: form.titulo.trim(),
      arquivo: form.arquivo.trim(),
      categoria: form.categoria,
      ativo: form.ativo ? 1 : 0,
    };

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

  const handleDelete = (v: PodcastVinheta) => {
    if (!window.confirm(`Excluir a vinheta "${v.titulo}"?`)) return;
    deletarMutation.mutate({ id: v.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?.length ?? 0} vinheta(s) cadastrada(s)</p>
        <Button onClick={openNew} className="bg-sof-borgonha hover:bg-sof-borgonha-dark text-white">
          + Nova Vinheta
        </Button>
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Título</TableHead>
            <TableHead>Categoria</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?.length ? (
            data.map(v => (
              <TableRow key={v.id}>
                <TableCell className="font-medium">{v.titulo}</TableCell>
                <TableCell>{categoriaLabels[(v.categoria ?? "transicao") as VinhetaCategoria]}</TableCell>
                <TableCell>{v.ativo ? "Sim" : "Não"}</TableCell>
                <TableCell className="text-right space-x-2">
                  <Button size="sm" variant="outline" onClick={() => openEdit(v)}>
                    Editar
                  </Button>
                  <Button size="sm" variant="destructive" onClick={() => handleDelete(v)}>
                    Excluir
                  </Button>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={4} className="text-center text-sof-text-3">
                Nenhuma vinheta cadastrada.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>

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

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

            <FileUploadField
              label="Arquivo de áudio *"
              type="audio"
              value={form.arquivo}
              onChange={url => setForm(f => ({ ...f, arquivo: url }))}
            />

            <div className="space-y-2">
              <Label>Categoria</Label>
              <Select value={form.categoria} onValueChange={v => setForm(f => ({ ...f, categoria: v as VinhetaCategoria }))}>
                <SelectTrigger className="w-full">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="abertura">Abertura</SelectItem>
                  <SelectItem value="transicao">Transição (usada pelo AutoDJ)</SelectItem>
                  <SelectItem value="encerramento">Encerramento</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center gap-3">
              <Switch checked={form.ativo} onCheckedChange={checked => setForm(f => ({ ...f, ativo: checked }))} />
              <Label>Ativa</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>
  );
}
