import { useState } from "react";
import { trpc } from "@/providers/trpc";
import { Link } from "react-router-dom";
import {
  Plus, Copy, Check, Power, Trash2, RefreshCw,
  Eye, FileText, ChevronDown, ChevronUp
} from "lucide-react";

export default function AdminAreaCliente() {
  const utils = trpc.useUtils();
  const { data: forms, isLoading } = trpc.form.list.useQuery();
  const createMutation = trpc.form.create.useMutation({
    onSuccess: () => { utils.form.list.invalidate(); setShowCreate(false); }
  });
  const statusMutation = trpc.form.updateStatus.useMutation({
    onSuccess: () => utils.form.list.invalidate()
  });
  const deleteMutation = trpc.form.delete.useMutation({
    onSuccess: () => utils.form.list.invalidate()
  });
  const regenerateMutation = trpc.form.regenerateCode.useMutation({
    onSuccess: () => utils.form.list.invalidate()
  });

  const [showCreate, setShowCreate] = useState(false);
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [expandedForm, setExpandedForm] = useState<string | null>(null);
  const [formData, setFormData] = useState({ title: "", description: "", clientName: "", clientEmail: "" });

  const copyCode = (code: string) => {
    navigator.clipboard.writeText(`${window.location.origin}/formulario/${code}`);
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 2000);
  };

  const handleCreate = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.title || !formData.clientName) return;
    createMutation.mutate(formData);
  };

  const statusColors = {
    active: "bg-green-500/20 text-green-400 border-green-500/30",
    inactive: "bg-yellow-500/20 text-yellow-400 border-yellow-500/30",
    archived: "bg-gray-500/20 text-gray-400 border-gray-500/30",
  };

  const statusLabels = {
    active: "Ativo",
    inactive: "Inativo",
    archived: "Arquivado",
  };

  return (
    <div className="min-h-screen bg-[#0e0e0e] text-white">
      <div className="max-w-6xl mx-auto px-6 py-12">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold">
              <span className="text-[#cbf400]">Area</span> do Cliente
            </h1>
            <p className="text-gray-400 mt-1">Painel administrativo - Gestao de formularios</p>
          </div>
          <Link to="/" className="text-gray-400 hover:text-[#cbf400] transition-colors text-sm">
            Voltar ao site
          </Link>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-3 gap-4 mb-8">
          <div className="bg-[#1a1a1a] rounded-xl p-4 border border-[#2a2a2a]">
            <div className="text-2xl font-bold text-[#cbf400]">{forms?.length || 0}</div>
            <div className="text-gray-400 text-sm">Formularios</div>
          </div>
          <div className="bg-[#1a1a1a] rounded-xl p-4 border border-[#2a2a2a]">
            <div className="text-2xl font-bold text-green-400">
              {forms?.filter(f => f.status === "active").length || 0}
            </div>
            <div className="text-gray-400 text-sm">Ativos</div>
          </div>
          <div className="bg-[#1a1a1a] rounded-xl p-4 border border-[#2a2a2a]">
            <div className="text-2xl font-bold text-yellow-400">
              {forms?.filter(f => f.status === "inactive").length || 0}
            </div>
            <div className="text-gray-400 text-sm">Inativos</div>
          </div>
        </div>

        {/* Criar Formulario */}
        <button
          onClick={() => setShowCreate(!showCreate)}
          className="mb-6 bg-[#cbf400] text-[#0e0e0e] px-5 py-2.5 rounded-xl font-semibold hover:bg-[#b8e000] transition-colors flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          Novo Formulario
        </button>

        {showCreate && (
          <form onSubmit={handleCreate} className="bg-[#1a1a1a] rounded-2xl p-6 border border-[#2a2a2a] mb-8">
            <h3 className="text-lg font-semibold mb-4">Criar Novo Formulario</h3>
            <div className="grid md:grid-cols-2 gap-4">
              <input
                type="text"
                placeholder="Titulo do formulario *"
                required
                value={formData.title}
                onChange={e => setFormData({ ...formData, title: e.target.value })}
                className="bg-[#0e0e0e] border border-[#2a2a2a] rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-[#cbf400] focus:outline-none"
              />
              <input
                type="text"
                placeholder="Nome do cliente *"
                required
                value={formData.clientName}
                onChange={e => setFormData({ ...formData, clientName: e.target.value })}
                className="bg-[#0e0e0e] border border-[#2a2a2a] rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-[#cbf400] focus:outline-none"
              />
              <input
                type="email"
                placeholder="Email do cliente"
                value={formData.clientEmail}
                onChange={e => setFormData({ ...formData, clientEmail: e.target.value })}
                className="bg-[#0e0e0e] border border-[#2a2a2a] rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-[#cbf400] focus:outline-none"
              />
              <input
                type="text"
                placeholder="Descricao (opcional)"
                value={formData.description}
                onChange={e => setFormData({ ...formData, description: e.target.value })}
                className="bg-[#0e0e0e] border border-[#2a2a2a] rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-[#cbf400] focus:outline-none"
              />
            </div>
            <div className="flex gap-3 mt-4">
              <button type="submit" disabled={createMutation.isPending}
                className="bg-[#cbf400] text-[#0e0e0e] px-6 py-2.5 rounded-xl font-semibold hover:bg-[#b8e000] transition-colors disabled:opacity-50">
                {createMutation.isPending ? "Criando..." : "Criar Formulario"}
              </button>
              <button type="button" onClick={() => setShowCreate(false)}
                className="border border-[#2a2a2a] text-gray-400 px-6 py-2.5 rounded-xl hover:bg-[#2a2a2a] transition-colors">
                Cancelar
              </button>
            </div>
            {createMutation.isSuccess && (
              <div className="mt-4 p-4 bg-green-500/10 border border-green-500/30 rounded-xl">
                <p className="text-green-400 font-medium">Formulario criado!</p>
                <p className="text-gray-400 text-sm mt-1">
                  Codigo: <span className="text-[#cbf400] font-mono">{createMutation.data?.code}</span>
                </p>
                <p className="text-gray-400 text-sm">
                  URL: <span className="text-[#cbf400]">{window.location.origin}/formulario/{createMutation.data?.code}</span>
                </p>
              </div>
            )}
          </form>
        )}

        {/* Lista de Formularios */}
        {isLoading ? (
          <div className="flex justify-center py-12">
            <div className="w-8 h-8 border-2 border-[#cbf400] border-t-transparent rounded-full animate-spin" />
          </div>
        ) : !forms?.length ? (
          <div className="text-center py-16 text-gray-500">
            <FileText className="w-12 h-12 mx-auto mb-4 opacity-30" />
            <p>Nenhum formulario criado ainda.</p>
          </div>
        ) : (
          <div className="space-y-4">
            {forms.map(form => (
              <div key={form.accessCode} className="bg-[#1a1a1a] rounded-2xl border border-[#2a2a2a] overflow-hidden">
                {/* Header do card */}
                <div className="p-5 flex items-center justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-1">
                      <h3 className="font-semibold text-white">{form.title}</h3>
                      <span className={`px-2 py-0.5 rounded text-xs font-medium border ${statusColors[form.status]}`}>
                        {statusLabels[form.status]}
                      </span>
                    </div>
                    <p className="text-gray-400 text-sm">{form.clientName}</p>
                    <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                      <span>Codigo: <span className="text-[#cbf400] font-mono">{form.accessCode}</span></span>
                      <span>Criado: {new Date(form.createdAt).toLocaleDateString('pt-BR')}</span>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {/* Copiar URL */}
                    <button
                      onClick={() => copyCode(form.accessCode)}
                      className="p-2 rounded-lg bg-[#2a2a2a] text-gray-400 hover:text-[#cbf400] hover:bg-[#333] transition-colors"
                      title="Copiar URL do formulario"
                    >
                      {copiedCode === form.accessCode ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
                    </button>

                    {/* Ativar/Desativar */}
                    <button
                      onClick={() => statusMutation.mutate({
                        accessCode: form.accessCode,
                        status: form.status === "active" ? "inactive" : "active"
                      })}
                      className={`p-2 rounded-lg transition-colors ${
                        form.status === "active"
                          ? "bg-green-500/10 text-green-400 hover:bg-green-500/20"
                          : "bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20"
                      }`}
                      title={form.status === "active" ? "Desativar" : "Ativar"}
                    >
                      <Power className="w-4 h-4" />
                    </button>

                    {/* Renovar codigo */}
                    <button
                      onClick={() => { if (confirm("Gerar novo codigo? O antigo deixara de funcionar.")) regenerateMutation.mutate({ accessCode: form.accessCode }); }}
                      className="p-2 rounded-lg bg-[#2a2a2a] text-gray-400 hover:text-blue-400 hover:bg-[#333] transition-colors"
                      title="Renovar codigo"
                    >
                      <RefreshCw className="w-4 h-4" />
                    </button>

                    {/* Excluir */}
                    <button
                      onClick={() => { if (confirm("Excluir permanentemente?")) deleteMutation.mutate({ accessCode: form.accessCode }); }}
                      className="p-2 rounded-lg bg-[#2a2a2a] text-gray-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                      title="Excluir"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>

                    {/* Expandir */}
                    <button
                      onClick={() => setExpandedForm(expandedForm === form.accessCode ? null : form.accessCode)}
                      className="p-2 rounded-lg bg-[#2a2a2a] text-gray-400 hover:text-white hover:bg-[#333] transition-colors"
                    >
                      {expandedForm === form.accessCode ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                    </button>
                  </div>
                </div>

                {/* Detalhes expandidos */}
                {expandedForm === form.accessCode && (
                  <div className="px-5 pb-5 border-t border-[#2a2a2a]">
                    <div className="pt-4">
                      <p className="text-gray-400 text-sm mb-3">{form.description}</p>
                      <div className="flex gap-3">
                        <Link
                          to={`/formulario/${form.accessCode}`}
                          target="_blank"
                          className="inline-flex items-center gap-2 text-sm text-[#cbf400] hover:underline"
                        >
                          <Eye className="w-4 h-4" />
                          Visualizar formulario
                        </Link>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
