import React, { useState } from 'react';
import { ItemDetailPanel } from './ItemDetailPanel';
import { 
  FileText, 
  Trash2, 
  Edit, 
  Mail, 
  Printer, 
  User,
  MapPin,
  Phone,
  Settings,
  AlertCircle,
  Plus,
  ArrowLeft,
  Save
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';

// --- MOCK COMPONENTS (TEST ONLY) ---

// 1. Mock EDIT Form (Updates existing data)
const MockEditForm = ({ initialData, onSave, onCancel }) => {
  return (
    <Card className="border-none shadow-none animate-in fade-in zoom-in-95 duration-200">
      <CardHeader className="px-0 pt-0">
        <div className="flex items-center gap-2">
            <div className="p-2 bg-amber-500/10 rounded-full text-amber-500">
                <Edit className="w-4 h-4" />
            </div>
            <div>
                <CardTitle className="text-lg">Editar Informações</CardTitle>
                <CardDescription>Alterações impactam relatórios imediatamente.</CardDescription>
            </div>
        </div>
      </CardHeader>
      <CardContent className="px-0 space-y-4">
        <div className="space-y-3">
          <Label className="uppercase text-[10px] font-bold text-slate-500 tracking-widest">Dados Cadastrais</Label>
          <div className="space-y-2">
            <Label htmlFor="nome">Nome / Razão Social</Label>
            <Input id="nome" defaultValue={initialData.clientName || initialData.title} className="bg-white dark:bg-black/20" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
                <Label htmlFor="doc">Documento (CPF/CNPJ)</Label>
                <Input id="doc" defaultValue={initialData.subtitle} disabled className="bg-muted" />
            </div>
             <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <Select defaultValue={initialData.status === 'Ativo' ? "ativo" : "pendente"}>
                    <SelectTrigger className="bg-white dark:bg-black/20">
                        <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="ativo">Ativo</SelectItem>
                        <SelectItem value="suspenso">Suspenso</SelectItem>
                        <SelectItem value="pendente">Pendente</SelectItem>
                    </SelectContent>
                </Select>
            </div>
          </div>
        </div>
        
        <Separator />
        
        <div className="space-y-3">
            <Label className="uppercase text-[10px] font-bold text-slate-500 tracking-widest">Contato</Label>
            <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                    <Label htmlFor="email">E-mail</Label>
                    <Input id="email" defaultValue={initialData.details?.email} className="bg-white dark:bg-black/20" />
                </div>
                <div className="space-y-2">
                    <Label htmlFor="tel">Telefone</Label>
                    <Input id="tel" defaultValue={initialData.details?.telefone} className="bg-white dark:bg-black/20" />
                </div>
            </div>
        </div>
      </CardContent>
      <CardFooter className="px-0 flex justify-end gap-2 pt-4">
        <Button variant="ghost" onClick={onCancel} className="text-slate-500">Cancelar</Button>
        <Button onClick={() => onSave({ ...initialData })} className="bg-emerald-600 hover:bg-emerald-700 text-white gap-2">
            <Save className="w-4 h-4" /> Salvar
        </Button>
      </CardFooter>
    </Card>
  )
};

// 2. Mock CREATE Form (New Item)
const MockCreateForm = ({ onCancel, onSave }) => {
    return (
        <Card className="border-none shadow-none animate-in slide-in-from-right-4 duration-300">
             <CardHeader className="px-0 pt-0">
                <div className="flex items-center gap-2">
                    <div className="p-2 bg-emerald-500/10 rounded-full text-emerald-500">
                        <Plus className="w-4 h-4" />
                    </div>
                    <div>
                        <CardTitle className="text-lg">Novo Cadastro</CardTitle>
                        <CardDescription>Preencha os dados para registrar um novo item.</CardDescription>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="px-0 space-y-6">
                
                {/* Step 1 */}
                <div className="space-y-4 p-4 border rounded-lg bg-slate-50 dark:bg-white/5 border-dashed border-slate-300 dark:border-white/10">
                    <div className="space-y-2">
                        <Label htmlFor="new-name">Nome Completo <span className="text-red-500">*</span></Label>
                        <Input id="new-name" placeholder="Ex: João da Silva" />
                    </div>
                     <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                            <Label htmlFor="new-cpf">CPF/CNPJ <span className="text-red-500">*</span></Label>
                            <Input id="new-cpf" placeholder="000.000.000-00" />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="new-type">Tipo</Label>
                             <Select defaultValue="pessoa_fisica">
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="pessoa_fisica">Pessoa Física</SelectItem>
                                    <SelectItem value="pessoa_juridica">Pessoa Jurídica</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                </div>

                {/* Step 2 */}
                 <div className="space-y-4">
                    <Label className="text-muted-foreground uppercase text-[10px] font-bold tracking-widest">Informações Adicionais</Label>
                    <div className="grid grid-cols-2 gap-4">
                         <div className="space-y-2">
                            <Label htmlFor="new-email">E-mail</Label>
                            <Input id="new-email" placeholder="nome@exemplo.com" />
                        </div>
                         <div className="space-y-2">
                            <Label htmlFor="new-tel">Telefone</Label>
                            <Input id="new-tel" placeholder="(00) 00000-0000" />
                        </div>
                    </div>
                 </div>

            </CardContent>
            <CardFooter className="px-0 flex justify-between pt-6 border-t mt-4">
                <Button variant="ghost" onClick={onCancel}>Cancelar</Button>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={onCancel}>Salvar Rascunho</Button>
                    <Button onClick={onSave} className="bg-emerald-600 hover:bg-emerald-700 min-w-[120px]">
                        Criar Registro
                    </Button>
                </div>
            </CardFooter>
        </Card>
    )
}

// 3. Mock Data Display (Read Only)
const GeneralDetails = ({ data }) => (
  <div className="grid gap-6 animate-in fade-in duration-500">
    <div className="grid gap-1">
        <h4 className="text-xs font-bold text-muted-foreground uppercase tracking-widest mb-2 flex items-center gap-2">
            <User className="w-3 h-3" /> Identificação
        </h4>
        <div className="grid grid-cols-2 gap-4 bg-muted/30 p-4 rounded-lg border border-transparent hover:border-border transition-colors">
            <div>
                <span className="text-[10px] text-muted-foreground uppercase">Nome / Razão Social</span>
                <p className="text-sm font-medium text-foreground">{data.razao_social || data.clientName || '---'}</p>
            </div>
             <div>
                <span className="text-[10px] text-muted-foreground uppercase">Data Cadastro</span>
                <p className="text-sm font-medium text-foreground">{data.data_cadastro || "01/01/2023"}</p>
            </div>
        </div>
    </div>

    <div className="grid gap-1">
        <h4 className="text-xs font-bold text-muted-foreground uppercase tracking-widest mb-2 flex items-center gap-2">
            <MapPin className="w-3 h-3" /> Endereço & Contato
        </h4>
         <div className="bg-muted/30 p-4 rounded-lg space-y-3 border border-transparent hover:border-border transition-colors">
             <div className="grid grid-cols-1 gap-4">
                <div>
                    <span className="text-[10px] text-muted-foreground uppercase">E-mail</span>
                    <p className="text-sm font-medium truncate" title={data.email}>
                        {data.email}
                    </p>
                </div>
                <div>
                    <span className="text-[10px] text-muted-foreground uppercase">Telefone</span>
                     <p className="text-sm font-medium flex items-center gap-2">
                        {data.telefone}
                    </p>
                </div>
            </div>
            <Separator className="bg-slate-200 dark:bg-slate-700" />
            <div>
                <span className="text-[10px] text-muted-foreground uppercase">Logradouro</span>
                <p className="text-sm font-medium">{data.endereco}, {data.cidade}</p>
            </div>
         </div>
    </div>
  </div>
);


export const ItemDetailPanelDebug = () => {
  const [isOpen, setIsOpen] = useState(true);
  
  // State Machine: 'view' | 'edit' | 'create'
  const [mode, setMode] = useState('view'); 
  const [activeMock, setActiveMock] = useState('client');

  const mocks = {
    client: {
      clientName: "Empresa Exemplo LTDA",
      razao_social: "Empresa Exemplo Comércio e Serviços LTDA",
      subtitle: "CNPJ: 12.345.678/0001-90",
      status: "Ativo",
      statusColor: "bg-emerald-500/10 text-emerald-500",
      details: {
        email: "financeiro@empresa.com",
        telefone: "(11) 3344-5566",
        endereco: "Av. Paulista, 1000 - Conj 12",
        cidade: "São Paulo - SP",
        responsavel: "Carlos Eduardo",
        contrato: "Enterprise 2024",
        vencimento: "Dia 15"
      },
      invoices: [
        { id: "FAT-001", date: "15/01/2024", value: "R$ 2.500,00", status: "Pago", type: "Mensalidade" },
        { id: "FAT-002", date: "15/02/2024", value: "R$ 2.500,00", status: "Pago", type: "Mensalidade" },
      ]
    },
    service: {
      clientName: "Manutenção Corretiva",
      subtitle: "ORD-2024-882",
      status: "Aguardando Peças",
      statusColor: "bg-amber-500/10 text-amber-500",
      details: {
        veiculo: "VW Gol 1.6 MSI",
        placa: "ABC-1234",
        oficina: "Oficina Central",
        data_entrada: "10/03/2024",
        previsao: "20/03/2024",
        email: "oficina@central.com",
        telefone: "(11) 9999-8888",
        endereco: "Rua das Oficinas, 200",
        cidade: "Osasco - SP"
      },
      invoices: []
    }
  };

  const currentData = mocks[activeMock];
  const isCreating = mode === 'create';
  const isEditing = mode === 'edit';

  const handleSave = (newData) => {
    console.log("Saving data:", newData);
    setMode('view');
  };

  const handleCreate = (newData) => {
    console.log("Created new item:", newData);
    setMode('view');
    // In a real app, you'd set the active mock to the new item here
  };

  // --- TABS ---

  // For Creation Mode: Simplified Tab Structure
  const creationTabs = [
      {
          id: 'new-record',
          label: 'Cadastro',
          content: <MockCreateForm onCancel={() => setMode('view')} onSave={handleCreate} />
      }
  ];

  // For View/Edit Mode: Full Tab Structure
  const viewTabs = [
    {
      id: "details",
      label: "Visão Geral",
      content: isEditing 
        ? <MockEditForm initialData={currentData} onSave={handleSave} onCancel={() => setMode('view')} />
        : <GeneralDetails data={currentData.details} />
    },
    {
      id: "financial",
      label: "Financeiro",
      content: (
        <div className="space-y-4">
             <div className="flex justify-between items-center">
                 <h3 className="font-bold text-sm">Cobranças</h3>
                 <Button size="sm" variant="ghost" className="h-7 text-xs"><Plus className="w-3 h-3 mr-1"/> Add</Button>
             </div>
             {currentData.invoices.length > 0 ? (
                 <div className="space-y-2">
                    {currentData.invoices.map((inv, i) => (
                        <div key={i} className="flex items-center justify-between p-3 border rounded-lg bg-background hover:bg-muted/50 transition-colors cursor-pointer">
                            <div className="flex items-center gap-3">
                                <div className={`w-8 h-8 rounded-full flex items-center justify-center ${inv.status === 'Pago' ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-500'}`}>
                                    <FileText size={14} />
                                </div>
                                <div className="space-y-0.5">
                                    <p className="text-sm font-bold leading-none">{inv.id}</p>
                                    <p className="text-[10px] text-muted-foreground leading-none">{inv.date}</p>
                                </div>
                            </div>
                            <div className="text-right">
                                <p className="text-sm font-mono font-medium leading-none mb-1">{inv.value}</p>
                                <span className={`text-[9px] uppercase font-bold px-1.5 py-0.5 rounded ${inv.status === 'Pago' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
                                    {inv.status}
                                </span>
                            </div>
                        </div>
                    ))}
                 </div>
             ) : (
                <div className="text-center p-6 bg-muted/20 border border-dashed rounded-lg">
                    <p className="text-xs text-muted-foreground">Sem histórico financeiro.</p>
                </div>
             )}
        </div>
      )
    }
  ];

  // --- ACTIONS ---

  const viewActions = [
    {
      label: "Editar",
      icon: <Edit className="h-4 w-4" />,
      onClick: () => setMode('edit'),
      variant: 'outline'
    },
    {
      label: "Exportar",
      icon: <Printer className="h-4 w-4" />,
      onClick: () => console.log("Export click"),
      variant: "ghost"
    },
  ];

  const editActions = []; // No top actions in edit mode (save is in the form)
  
  const createActions = []; // No top actions in create mode

  const activeActions = isCreating ? createActions : (isEditing ? editActions : viewActions);
  const activeTabs = isCreating ? creationTabs : viewTabs;


  return (
    <div className="h-screen w-full flex overflow-hidden bg-slate-100 dark:bg-black font-sans">
      
      {/* Sidebar Controls */}
      <div className="w-80 shrink-0 border-r bg-white dark:bg-[#111] p-6 flex flex-col gap-6 overflow-y-auto shadow-xl z-10">
        <div>
            <h2 className="font-black text-xl tracking-tighter uppercase italic text-emerald-500">Playground</h2>
            <p className="text-xs text-muted-foreground font-medium mt-1">Laboratory Mode</p>
        </div>

        <div className="space-y-6 flex-1">
             <div className="space-y-3">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">Operating Mode</Label>
                <div className="grid grid-cols-2 gap-2">
                    <Button 
                        size="sm" 
                        variant={!isCreating ? "default" : "outline"}
                        onClick={() => { setMode('view'); setIsOpen(true); }}
                        className="w-full"
                    >
                        View / Edit
                    </Button>
                    <Button 
                        size="sm" 
                        variant={isCreating ? "default" : "outline"}
                        onClick={() => { setMode('create'); setIsOpen(true); }}
                        className={isCreating ? "bg-emerald-600 hover:bg-emerald-700 text-white" : "hover:text-emerald-500 hover:border-emerald-500"}
                    >
                        <Plus className="w-4 h-4 mr-1" /> Create
                    </Button>
                </div>
             </div>

             {!isCreating && (
                 <div className="space-y-3 animate-in fade-in slide-in-from-left-4">
                    <Label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">Scenario Data</Label>
                    <Select value={activeMock} onValueChange={setActiveMock}>
                        <SelectTrigger>
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="client">Client (Corp)</SelectItem>
                            <SelectItem value="service">Service Order</SelectItem>
                        </SelectContent>
                    </Select>
                 </div>
             )}

             <Separator />

             <div className="p-3 rounded-md bg-muted/50 border text-xs font-mono space-y-1">
                 <div className="flex justify-between">
                     <span className="text-muted-foreground">Mode:</span>
                     <span className="font-bold text-orange-500">{mode}</span>
                 </div>
                 <div className="flex justify-between">
                     <span className="text-muted-foreground">Mock:</span>
                     <span className="font-bold text-blue-500">{activeMock}</span>
                 </div>
             </div>
        </div>

        <Button variant="secondary" onClick={() => setIsOpen(!isOpen)} className="w-full">
            {isOpen ? 'Minimize Panel' : 'Restore Panel'}
        </Button>
      </div>


      {/* Main Preview Area */}
      <div className="flex-1 overflow-y-auto p-12 flex justify-center items-start bg-slate-50 dark:bg-black relative">
        {/* Grid Background Pattern */}
        <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px]"></div>
        
        {isOpen ? (
          <div className="relative z-10 transition-all duration-500 animate-in fade-in slide-in-from-bottom-8">
              <ItemDetailPanel
                // Props change based on mode
                title={isCreating ? "Novo Item" : currentData.clientName}
                subtitle={isCreating ? "Preencha os dados abaixo" : currentData.subtitle}
                status={isCreating ? null : currentData.status}
                statusColor={isCreating ? null : currentData.statusColor}
                
                actions={activeActions}
                menuActions={!isCreating ? [{ label: "Histórico", onClick: () => {} }] : []}
                tabs={activeTabs}
                
                onClose={() => setIsOpen(false)}
                className="w-[500px] shadow-2xl border-t border-white/10 ring-1 ring-black/5"
              />
          </div>
        ) : (
            <div className="flex flex-col items-center justify-center text-muted-foreground mt-40 z-10">
                <div className="w-20 h-20 bg-muted rounded-full flex items-center justify-center mb-4">
                    <Settings size={40} className="opacity-20" />
                </div>
                <p className="font-medium">Panel Minimized</p>
                <Button variant="link" onClick={() => setIsOpen(true)}>Restore</Button>
            </div>
        )}
      </div>

    </div>
  );
};

export default ItemDetailPanelDebug;
