import React, { useState, useMemo } from 'react';
import { useAutoLab } from '../hooks/useAutoLab';
// Importação local do ExcelTable para garantir isolamento total conforme Regra de Ouro
import ExcelTable from '../components/ExcelTable';
import { AutoLabDetailPanel } from '../components/AutoLabDetailPanel';
import { 
  Plus, FileText, ShoppingCart, Clock, ClipboardCheck,
  User, Package, Calendar, Info, Mail, Phone, 
  Settings, Image, List, Save, Trash2, Tag, Hash, File
} from 'lucide-react';
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { toast } from 'sonner';

export const VendasView = () => {
  const { data: vendas, loading } = useAutoLab('vendas');
  const [activeTab, setActiveTab] = useState('orcamentos');
  const [selectedVenda, setSelectedVenda] = useState(null);
  const [isPanelOpen, setIsPanelOpen] = useState(false);

  const handleRowClick = (row) => {
    setSelectedVenda(row);
    setIsPanelOpen(true);
  };

  const vendasColumns = [
    { header: 'Cliente', field: 'cliente', width: '250px', className: 'font-bold' },
    { header: 'Data', field: 'data', width: '100px' },
    { header: 'Digitador', field: 'digitador', width: '100px' },
    { header: 'Email', field: 'email', width: '200px' },
    { header: 'Equipamento', field: 'equipamento', width: '150px' },
    { header: 'Frete', field: 'frete', width: '100px' },
    { header: 'Frota', field: 'frota', width: '80px' },
    { header: 'Hora', field: 'hora', width: '100px' },
    { header: 'Cód. Solicitação', field: 'id_solicitacao', width: '120px', className: 'font-bold text-emerald-600' },
    { header: 'Modelo', field: 'modelo', width: '100px' },
    { header: 'Placa', field: 'placa', width: '100px', className: 'font-mono' },
    { header: 'Prazo Entrega', field: 'prazo_entrega', width: '120px' },
    { header: 'Resp. Orç.', field: 'responsavel_orcamento', width: '120px' },
  ];

  return (
    <div className="flex flex-col h-full bg-gradient-to-br from-slate-50 via-white to-slate-50/50 dark:from-[#0f0f0f] dark:via-[#1b1b1b] dark:to-[#0f0f0f]">
      {/* Premium Header Section */}
      <div className="relative p-6 border-b border-slate-200/80 dark:border-zinc-800/50 bg-gradient-to-r from-white via-slate-50/30 to-white dark:from-[#1b1b1b] dark:via-zinc-900/30 dark:to-[#1b1b1b] backdrop-blur-sm">
        <div className="absolute inset-0 bg-gradient-to-r from-orange-500/5 via-transparent to-emerald-500/5 dark:from-orange-500/10 dark:via-transparent dark:to-emerald-500/10" />
        
        <div className="relative flex flex-wrap items-center justify-between gap-6">
          {/* Tabs Section - Enhanced */}
          <div className="flex items-center gap-4 flex-1 min-w-0">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full min-w-0">
              <TabsList className="bg-slate-100/80 dark:bg-zinc-900/80 backdrop-blur-sm p-1.5 rounded-2xl border border-slate-200/50 dark:border-zinc-800/50 shadow-lg shadow-black/5 dark:shadow-black/20 gap-1.5 h-auto overflow-x-auto no-scrollbar">
                <TabsTrigger 
                  value="orcamentos" 
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-[#1b4332] data-[state=active]:to-[#2d6a4f] data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-emerald-900/30 rounded-xl px-5 py-2.5 transition-all duration-300 uppercase text-[11px] font-bold shrink-0 hover:bg-slate-200/50 dark:hover:bg-zinc-800/50"
                >
                  <FileText size={18} className="mr-2" /> Orçamentos
                </TabsTrigger>
                <TabsTrigger 
                  value="realizadas" 
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-[#1b4332] data-[state=active]:to-[#2d6a4f] data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-emerald-900/30 rounded-xl px-5 py-2.5 transition-all duration-300 uppercase text-[11px] font-bold shrink-0 hover:bg-slate-200/50 dark:hover:bg-zinc-800/50"
                >
                  <ShoppingCart size={18} className="mr-2" /> Vendas Realizadas
                </TabsTrigger>
                <TabsTrigger 
                  value="os" 
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-[#1b4332] data-[state=active]:to-[#2d6a4f] data-[state=active]:text-white data-[state=active]:shadow-lg data-[state=active]:shadow-emerald-900/30 rounded-xl px-5 py-2.5 transition-all duration-300 uppercase text-[11px] font-bold shrink-0 hover:bg-slate-200/50 dark:hover:bg-zinc-800/50"
                >
                  <ClipboardCheck size={18} className="mr-2" /> Ordem de Serviço
                </TabsTrigger>
              </TabsList>
            </Tabs>
          </div>

          {/* Action Button - Premium Style */}
          <div className="flex items-center gap-3">
            <Button className="bg-gradient-to-r from-[#1b4332] to-[#2d6a4f] hover:from-[#2d6a4f] hover:to-[#40916c] text-white rounded-xl px-6 py-3 font-bold shadow-xl shadow-emerald-900/25 hover:shadow-2xl hover:shadow-emerald-900/40 flex items-center gap-2.5 uppercase text-[11px] transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]">
              <Plus size={20} className="drop-shadow-sm" /> Novo Orçamento
            </Button>
          </div>
        </div>
      </div>

      {/* Table Container - Enhanced */}
      <div className="flex-1 overflow-hidden p-6 pt-4">
        <div className="h-full rounded-2xl border border-slate-200/60 dark:border-zinc-800/60 bg-white/80 dark:bg-[#1b1b1b]/80 backdrop-blur-sm shadow-xl shadow-black/5 dark:shadow-black/20 overflow-hidden">
          <ExcelTable 
            data={vendas} 
            loading={loading}
            columns={vendasColumns}
            onRowClick={handleRowClick}
            rowKey="id"
          />
        </div>
      </div>

      {/* Slide-over Detail Panel */}
      <AutoLabDetailPanel
        isOpen={isPanelOpen}
        onClose={() => setIsPanelOpen(false)}
        title={selectedVenda?.cliente || 'Detalhes da Venda'}
        subtitle={`Solicitação #${selectedVenda?.id_solicitacao || ''}`}
        status={selectedVenda?.status}
        statusColor="bg-orange-500/10 text-orange-600"
        actions={[
          { label: 'Salvar', onClick: () => toast.success('Venda Salva!'), variant: 'default', className: 'bg-[#1b4332] hover:bg-[#2d6a4f] text-white' },
          { label: 'Excluir', onClick: () => toast.error('Solicitação excluída'), isDestructive: true }
        ]}
        tabs={[
          {
            id: 'detalhes',
            label: 'Detalhes',
            content: (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                   <DetailItem label="Aplicação:" value={selectedVenda?.aplicacao} />
                   <DetailItem label="Data:" value={selectedVenda?.data} />
                   <DetailItem label="Desconto:" value={selectedVenda?.desconto} />
                   <DetailItem label="Digitador:" value={selectedVenda?.digitador} />
                   <DetailItem label="Email:" value={selectedVenda?.email} />
                   <DetailItem label="Equipamento:" value={selectedVenda?.equipamento} />
                   <DetailItem label="Frete:" value={selectedVenda?.frete} />
                   <DetailItem label="Frota:" value={selectedVenda?.frota} />
                   <DetailItem label="Garantia:" value={selectedVenda?.garantia} />
                   <DetailItem label="Hora:" value={selectedVenda?.hora} />
                   <DetailItem label="Cod. Solicitação:" value={selectedVenda?.id_solicitacao} />
                   <DetailItem label="Cod. Cliente:" value={selectedVenda?.cod_cliente} />
                   <DetailItem label="Info:" value={selectedVenda?.info_cliente} />
                   <DetailItem label="Modelo:" value={selectedVenda?.modelo} />
                   <DetailItem label="Placa:" value={selectedVenda?.placa} />
                   <DetailItem label="Prazo Entrega:" value={selectedVenda?.prazo_entrega} />
                   <DetailItem label="Resp. Orç.:" value={selectedVenda?.responsavel_orcamento} />
                </div>
                <div className="mt-4 p-5 bg-gradient-to-br from-slate-50/80 to-white dark:from-zinc-900/50 dark:to-zinc-800/30 rounded-xl border border-slate-200/60 dark:border-zinc-800/60 shadow-sm">
                    <span className="text-[10px] font-bold uppercase text-slate-500 dark:text-slate-400 tracking-wider">Descrição:</span>
                    <p className="text-sm mt-2 font-medium text-slate-700 dark:text-slate-300 leading-relaxed">{selectedVenda?.descricao || '---'}</p>
                </div>
              </div>
            )
          },
          {
            id: 'editar',
            label: 'Editar',
            content: (
              <div className="space-y-6">
                <Tabs defaultValue="base" className="w-full">
                  <TabsList className="bg-slate-100 dark:bg-zinc-800 p-1 rounded-lg w-full justify-start gap-1">
                    <TabsTrigger value="base" className="h-8 w-8 p-0 rounded-md data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-700 shadow-sm"><User size={16} /></TabsTrigger>
                    <TabsTrigger value="config" className="h-8 w-8 p-0 rounded-md data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-700 shadow-sm"><Settings size={16} /></TabsTrigger>
                    <TabsTrigger value="images" className="h-8 w-8 p-0 rounded-md data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-700 shadow-sm"><Image size={16} /></TabsTrigger>
                    <TabsTrigger value="items" className="h-8 w-8 p-0 rounded-md data-[state=active]:bg-white dark:data-[state=active]:bg-zinc-700 shadow-sm"><List size={16} /></TabsTrigger>
                  </TabsList>
                  
                  <div className="mt-6">
                    <TabsContent value="base" className="space-y-4">
                      <div className="grid grid-cols-2 gap-4">
                        <EditField label="Data:" value={selectedVenda?.data} />
                        <EditField label="Hora:" value={selectedVenda?.hora} />
                        <EditField label="Digitador:" value={selectedVenda?.digitador} />
                        <EditField label="Resp. Orçamento:" value={selectedVenda?.responsavel_orcamento} />
                        <EditField label="Placa:" value={selectedVenda?.placa} />
                        <EditField label="Modelo:" value={selectedVenda?.modelo} />
                        <EditField label="Frota:" value={selectedVenda?.frota} />
                        <EditField label="Equipamento:" value={selectedVenda?.equipamento} />
                        <EditField label="Aplicação:" value={selectedVenda?.aplicacao} />
                        <div className="col-span-2">
                           <EditField label="Cliente:" value={selectedVenda?.cliente} />
                        </div>
                      </div>
                    </TabsContent>

                    <TabsContent value="config" className="space-y-4">
                       <div className="space-y-4">
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-bold uppercase text-slate-400 ml-1">info_cliente:</label>
                            <textarea className="w-full bg-slate-50 dark:bg-zinc-950 border border-slate-200 dark:border-zinc-800 rounded-lg p-3 text-sm min-h-[100px]" defaultValue={selectedVenda?.info_cliente} />
                          </div>
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-bold uppercase text-slate-400 ml-1">relatorio_oficina:</label>
                            <textarea className="w-full bg-slate-50 dark:bg-zinc-950 border border-slate-200 dark:border-zinc-800 rounded-lg p-3 text-sm min-h-[100px]" defaultValue={selectedVenda?.relatorio_oficina} />
                          </div>
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-bold uppercase text-slate-400 ml-1">obs:</label>
                            <textarea className="w-full bg-slate-50 dark:bg-zinc-950 border border-slate-200 dark:border-zinc-800 rounded-lg p-3 text-sm min-h-[100px]" defaultValue={selectedVenda?.obs} />
                          </div>
                       </div>
                    </TabsContent>

                    <TabsContent value="images" className="space-y-4">
                       <div className="border-2 border-dashed border-slate-300/60 dark:border-zinc-700/60 rounded-2xl p-10 text-center space-y-3 bg-gradient-to-br from-slate-50/50 to-white dark:from-zinc-900/30 dark:to-zinc-800/20 hover:border-emerald-400/60 dark:hover:border-emerald-600/60 transition-all duration-300 hover:shadow-lg hover:shadow-emerald-500/10 group">
                          <label className="cursor-pointer block">
                            <div className="bg-gradient-to-br from-emerald-50 to-emerald-100/50 dark:from-emerald-900/30 dark:to-emerald-900/20 group-hover:from-emerald-100 group-hover:to-emerald-150 dark:group-hover:from-emerald-900/40 dark:group-hover:to-emerald-900/30 w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3 text-emerald-600 dark:text-emerald-400 transition-all duration-300 shadow-md group-hover:shadow-lg group-hover:scale-110">
                               <Plus size={28} strokeWidth={2.5} />
                            </div>
                            <span className="text-sm font-bold block text-slate-700 dark:text-slate-300">Anexar imagens</span>
                            <span className="text-xs text-slate-500 dark:text-slate-400">Arraste ou clique para selecionar</span>
                            <input type="file" className="hidden" multiple accept="image/*" />
                          </label>
                       </div>
                    </TabsContent>

                    <TabsContent value="items" className="space-y-6">
                        <div className="bg-gradient-to-br from-slate-50/80 to-white dark:from-zinc-900/50 dark:to-zinc-800/30 p-5 rounded-xl border border-slate-200/60 dark:border-zinc-800/60 shadow-sm space-y-4">
                           <div className="grid grid-cols-2 gap-4">
                              <EditField label="Preço:" value="-- Escolha uma opção --" select />
                              <EditField label="Item:" placeholder="Pesquisar Item..." />
                              <EditField label="Cod Peças:" />
                              <EditField label="Qtd Peças:" />
                              <EditField label="Unid Peças:" value="-- Escolha uma opção --" select />
                              <EditField label="Modelo:" />
                              <EditField label="Marca:" />
                              <EditField label="Fornecedor:" />
                              <EditField label="Preço Unitário:" />
                           </div>
                           <Button className="w-full bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-700 hover:to-emerald-800 text-white font-bold h-11 mt-2 shadow-lg shadow-emerald-900/25 hover:shadow-xl hover:shadow-emerald-900/40 transition-all duration-200 hover:scale-[1.01] active:scale-[0.99]">
                             Inserir
                           </Button>
                        </div>

                        <div className="space-y-3">
                           <h4 className="text-[10px] font-bold uppercase text-slate-500 dark:text-slate-400 tracking-widest pl-1">Itens Adicionados</h4>
                           {selectedVenda?.items?.map(item => (
                             <div key={item.id} className="p-4 bg-gradient-to-br from-emerald-50/50 to-emerald-100/30 dark:from-emerald-900/20 dark:to-emerald-900/10 border border-emerald-200/50 dark:border-emerald-800/30 rounded-xl relative group hover:shadow-md hover:shadow-emerald-500/10 transition-all duration-300">
                                <p className="text-xs font-bold text-emerald-800 dark:text-emerald-400 pr-8">{item.item}</p>
                                <div className="grid grid-cols-3 gap-2 mt-2 text-[10px] text-slate-600 dark:text-slate-400 font-semibold">
                                   <span>Qtd: {item.qtd}</span>
                                   <span>Preço: {item.preco}</span>
                                   <span>Marca: {item.marca}</span>
                                </div>
                                <button className="absolute top-4 right-4 text-rose-500 dark:text-rose-400 opacity-0 group-hover:opacity-100 transition-all duration-200 p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-900/20 hover:scale-110 active:scale-95">
                                   <Trash2 size={16} strokeWidth={2.5} />
                                </button>
                             </div>
                           ))}
                        </div>
                    </TabsContent>
                  </div>
                </Tabs>
              </div>
            )
          }
        ]}
      />
    </div>
  );
};

// Helper components
const DetailItem = ({ label, value }) => (
  <div className="flex flex-col gap-2 p-4 rounded-xl bg-gradient-to-br from-slate-50/50 to-white dark:from-zinc-900/30 dark:to-zinc-800/20 border border-slate-200/50 dark:border-zinc-800/50 hover:border-orange-300/50 dark:hover:border-orange-700/50 transition-all duration-300 hover:shadow-md hover:shadow-orange-500/5 group">
    <span className="text-[10px] font-bold uppercase text-slate-500 dark:text-slate-400 tracking-wider leading-none">{label}</span>
    <span className="text-sm font-bold text-slate-800 dark:text-slate-100 drop-shadow-sm">{value || '---'}</span>
  </div>
);

const EditField = ({ label, value, placeholder, select }) => (
  <div className="space-y-2">
    <label className="text-[10px] font-bold uppercase text-slate-500 dark:text-slate-400 tracking-wider ml-1 leading-none">{label}</label>
    {select ? (
      <select className="w-full bg-gradient-to-br from-slate-50 to-white dark:from-zinc-950 dark:to-zinc-900 border border-slate-200/60 dark:border-zinc-800/60 rounded-xl px-4 h-11 text-xs font-semibold focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-400 dark:focus:border-emerald-600 outline-none transition-all duration-200 shadow-sm hover:shadow-md">
        <option>{value}</option>
      </select>
    ) : (
      <input 
        type="text" 
        className="w-full bg-gradient-to-br from-slate-50 to-white dark:from-zinc-950 dark:to-zinc-900 border border-slate-200/60 dark:border-zinc-800/60 rounded-xl px-4 h-11 text-xs font-semibold placeholder:text-slate-400 dark:placeholder:text-slate-500 focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-400 dark:focus:border-emerald-600 outline-none transition-all duration-200 shadow-sm hover:shadow-md" 
        defaultValue={value} 
        placeholder={placeholder}
      />
    )}
  </div>
);

const Separator = () => <div className="h-px w-full bg-slate-100 dark:bg-zinc-800" />;
