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

const NONE = "none";

type ProgramaForm = {
  titulo: string;
  slug: string;
  descricao: string;
  capa: string;
  ano: string;
  genero: string;
  categoria: string;
  apresentadorId: string;
  status: "rascunho" | "publicado" | "arquivado";
  configAutodj: boolean;
  configSequencial: boolean;
  configVinheta: boolean;
  ativo: boolean;
};

const emptyForm: ProgramaForm = {
  titulo: "",
  slug: "",
  descricao: "",
  capa: "",
  ano: "",
  genero: "",
  categoria: "podcast",
  apresentadorId: NONE,
  status: "publicado",
  configAutodj: true,
  configSequencial: true,
  configVinheta: false,
  ativo: true,
};

function toForm(p: PodcastPrograma): ProgramaForm {
  return {
    titulo: p.titulo,
    slug: p.slug ?? "",
    descricao: p.descricao ?? "",
    capa: p.capa ?? "",
    ano: p.ano != null ? String(p.ano) : "",
    genero: p.genero ?? "",
    categoria: p.categoria ?? "podcast",
    apresentadorId: p.apresentadorId != null ? String(p.apresentadorId) : NONE,
    status: p.status ?? "publicado",
    configAutodj: p.configAutodj === 1,
    configSequencial: p.configSequencial === 1,
    configVinheta: p.configVinheta === 1,
    ativo: p.ativo === 1,
  };
}

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

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

  const invalidate = () => {
    utils.podcast.admin.programas.listar.invalidate();
    utils.podcast.admin.stats.invalidate();
    utils.podcast.getProgramas.invalidate();
  };

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

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

  const deletarMutation = trpc.podcast.admin.programas.deletar.useMutation({
    onSuccess: () => {
      toast.success("Série 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 = (p: PodcastPrograma) => {
    setEditing(p);
    setForm(toForm(p));
    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,
      ano: form.ano ? Number(form.ano) : null,
      genero: form.genero.trim() || null,
      categoria: form.categoria.trim() || null,
      apresentadorId: form.apresentadorId === NONE ? null : Number(form.apresentadorId),
      status: form.status,
      configAutodj: form.configAutodj ? 1 : 0,
      configSequencial: form.configSequencial ? 1 : 0,
      configVinheta: form.configVinheta ? 1 : 0,
      ativo: form.ativo ? 1 : 0,
    };

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

  const handleDelete = (p: PodcastPrograma) => {
    if (!window.confirm(`Excluir a série "${p.titulo}"? Os episódios associados também serão removidos.`)) return;
    deletarMutation.mutate({ id: p.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} série(s) cadastrada(s)</p>
        <Button onClick={openNew} className="bg-sof-borgonha hover:bg-sof-borgonha-dark text-white">
          + Nova Série
        </Button>
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Título</TableHead>
            <TableHead>Categoria</TableHead>
            <TableHead>AutoDJ</TableHead>
            <TableHead>Ativo</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {isLoading ? (
            <TableRow>
              <TableCell colSpan={5} className="text-center text-sof-text-3">
                Carregando...
              </TableCell>
            </TableRow>
          ) : data?.programas.length ? (
            data.programas.map(p => (
              <TableRow key={p.id}>
                <TableCell className="font-medium max-w-xs truncate">{p.titulo}</TableCell>
                <TableCell className="capitalize">{p.categoria}</TableCell>
                <TableCell>{p.configAutodj ? "Sim" : "Não"}</TableCell>
                <TableCell>{p.ativo ? "Sim" : "Não"}</TableCell>
                <TableCell className="text-right space-x-2">
                  <Button size="sm" variant="outline" onClick={() => openEdit(p)}>
                    Editar
                  </Button>
                  <Button size="sm" variant="destructive" onClick={() => handleDelete(p)}>
                    Excluir
                  </Button>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={5} className="text-center text-sof-text-3">
                Nenhuma série cadastrada.
              </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-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? "Editar série" : "Nova série"}</DialogTitle>
          </DialogHeader>

          <form onSubmit={handleSubmit} 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 ProgramaForm["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>Ano</Label>
                <Input type="number" value={form.ano} onChange={e => setForm(f => ({ ...f, ano: e.target.value }))} />
              </div>

              <div className="space-y-2">
                <Label>Gênero</Label>
                <Input value={form.genero} onChange={e => setForm(f => ({ ...f, genero: e.target.value }))} />
              </div>

              <div className="space-y-2">
                <Label>Categoria</Label>
                <Input value={form.categoria} onChange={e => setForm(f => ({ ...f, categoria: e.target.value }))} />
              </div>

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

              <div className="col-span-2 border-t pt-4 mt-2">
                <p className="text-sm font-bold text-sof-text-2 mb-3">Configurações do AutoDJ</p>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>AutoDJ ativado</Label>
                      <p className="text-xs text-sof-text-3">
                        Ao terminar um episódio, o player toca automaticamente o próximo desta série.
                      </p>
                    </div>
                    <Switch
                      checked={form.configAutodj}
                      onCheckedChange={checked => setForm(f => ({ ...f, configAutodj: checked }))}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>Ordem sequencial</Label>
                      <p className="text-xs text-sof-text-3">
                        Tocar episódios em ordem (desligado = ordem aleatória).
                      </p>
                    </div>
                    <Switch
                      checked={form.configSequencial}
                      onCheckedChange={checked => setForm(f => ({ ...f, configSequencial: checked }))}
                    />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label>Vinheta de transição</Label>
                      <p className="text-xs text-sof-text-3">
                        Tocar uma vinheta de transição entre os episódios.
                      </p>
                    </div>
                    <Switch
                      checked={form.configVinheta}
                      onCheckedChange={checked => setForm(f => ({ ...f, configVinheta: checked }))}
                    />
                  </div>
                </div>
              </div>

              <div className="col-span-2 flex items-center gap-3 border-t pt-4">
                <Switch checked={form.ativo} onCheckedChange={checked => setForm(f => ({ ...f, ativo: checked }))} />
                <Label>Ativa (visível no site)</Label>
              </div>
            </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>
  );
}
