import React, { useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useWindStore } from '@/store/appStore';
import { calculatePiperack, type PipeDef } from '@/lib/modules/piperack';
import { Piperack3D } from '@/components/three/Piperack3D';
import SceneCapturePanel from '../components/SceneCapturePanel';
import ExportMenu from '../components/ExportMenu';
import { exportGenericToPDF, type GenericPDFSection } from '../lib/export-generic-pdf';
import { Plus, Trash2, Layers, Info } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip';
import { Input } from '@/components/ui/input';
import { EducationalManual } from '@/components/EducationalManual';

const PiperackModule: React.FC = () => {
  const { q } = useWindStore();
  const [width, setWidth] = useState(17);
  const [height, setHeight] = useState(2);
  const [elevation, setElevation] = useState(6);
  const [spacing, setSpacing] = useState(2);
  const [numFrames, setNumFrames] = useState(2);
  const [phiStruct, setPhiStruct] = useState(0.5);
  const [pipes, setPipes] = useState<PipeDef[]>([]);

  const addPipe = () => {
    setPipes([...pipes, { id: Math.random().toString(36).substr(2, 9), diameter: 0.5 }]);
  };

  const removePipe = (id: string) => {
    setPipes(pipes.filter(p => p.id !== id));
  };

  const updatePipe = (id: string, diam: number) => {
    setPipes(pipes.map(p => p.id === id ? { ...p, diameter: diam } : p));
  };

  const result = useMemo(() => {
    return calculatePiperack({
      width,
      height,
      elevation,
      spacing,
      numFrames,
      phiStruct,
      pipes,
      q,
    });
  }, [width, height, elevation, spacing, numFrames, phiStruct, pipes, q]);

  const handleExportPDF = () => {
    const sections: GenericPDFSection[] = [
      {
        title: 'Geometria do Pipe-Rack',
        type: 'grid',
        gridItems: [
          { label: 'Largura do pórtico (b)', value: `${width} m` },
          { label: 'Altura do pórtico (h)', value: `${height} m` },
          { label: 'Elevação média (z)', value: `${elevation} m` },
          { label: 'Espaçamento (e)', value: `${spacing} m` },
          { label: 'Número de pórticos (n)', value: String(numFrames) },
          { label: 'Solidez estrutural', value: phiStruct.toFixed(2) },
          { label: 'Quantidade de Tubos', value: String(pipes.length) },
        ],
      },
      {
        title: 'Coeficientes Aerodinâmicos',
        type: 'grid',
        gridItems: [
          { label: 'Solidez total (est. + tubos)', value: result.phiTotal.toFixed(2) },
          { label: 'Ca frontal', value: result.caFrontal.toFixed(2) },
          { label: 'Fator de proteção', value: result.eta.toFixed(2) },
        ],
      },
      {
        title: 'Forças e Momentos Globais',
        type: 'grid',
        gridItems: [
          { label: 'Carga Linear Pórtico Frontal', value: `${result.linearLoadFront.toFixed(2)} kN/m` },
          { label: 'Carga Linear Pórticos Traseiros (cada)', value: `${result.linearLoadBack.toFixed(2)} kN/m` },
          { label: 'Força Global Total', value: `${result.globalForce.toFixed(2)} kN` },
          { label: 'Momento Total de Tombamento', value: `${(result.linearLoadFront * width * elevation + (numFrames > 1 ? (numFrames - 1) * result.linearLoadBack * width * elevation : 0)).toFixed(2)} kN·m` },
        ],
      }
    ];

    exportGenericToPDF('Pipe-Racks Industriais', sections);
  };

  return (
    <div className="flex flex-col h-[calc(100vh-3.5rem)] md:h-screen bg-background">
      <header className="shrink-0 flex items-center justify-between px-6 py-4 border-b bg-card">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-primary/10 rounded-lg">
            <Layers className="w-5 h-5 text-primary" />
          </div>
          <div>
            <h1 className="text-xl font-bold tracking-tight">Pipe-Racks Industriais</h1>
            <p className="text-sm text-muted-foreground">Vento transversal (Sec. 7 - NBR 6123)</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <ExportMenu onExportPDF={handleExportPDF} />
        </div>
      </header>

      <div className="flex-1 flex flex-col lg:flex-row p-4 gap-4 overflow-hidden bg-muted/30">
        
        {/* Coluna Esquerda: Entradas */}
        <div className="w-full lg:w-80 shrink-0 overflow-y-auto bg-card rounded-xl border border-border shadow-sm p-5 space-y-6">
          <div>
            <h3 className="font-medium mb-4">Geometria da Estrutura</h3>
            <div className="space-y-5">
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm font-medium">Largura (b)</span>
                  <span className="text-sm text-muted-foreground">{width} m</span>
                </div>
                <Slider value={[width]} min={2} max={25} step={0.5} onValueChange={v => setWidth(v[0])} />
              </div>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm font-medium">Altura do pórtico (h)</span>
                  <span className="text-sm text-muted-foreground">{height} m</span>
                </div>
                <Slider value={[height]} min={0.5} max={5} step={0.1} onValueChange={v => setHeight(v[0])} />
              </div>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm font-medium">Elevação (z)</span>
                  <span className="text-sm text-muted-foreground">{elevation} m</span>
                </div>
                <Slider value={[elevation]} min={2} max={25} step={1} onValueChange={v => setElevation(v[0])} />
              </div>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm font-medium">Espaçamento (e)</span>
                  <span className="text-sm text-muted-foreground">{spacing} m</span>
                </div>
                <Slider value={[spacing]} min={0.5} max={5} step={0.5} onValueChange={v => setSpacing(v[0])} />
              </div>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm font-medium">Número de Pórticos (n)</span>
                  <span className="text-sm text-muted-foreground">{numFrames}</span>
                </div>
                <Slider value={[numFrames]} min={1} max={5} step={1} onValueChange={v => setNumFrames(v[0])} />
              </div>
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium">Índice de Solidez (φ str)</span>
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Info className="w-4 h-4 text-muted-foreground cursor-help" />
                        </TooltipTrigger>
                        <TooltipContent side="top" className="max-w-xs">
                          <p>O índice de solidez (φ) representa a relação entre a área efetivamente bloqueada pelos perfis do reticulado e a área total contornada pelo pórtico. Quanto mais "fechado" for o pórtico estrutural, maior o arrasto aerodinâmico (ref. Tabela 28 da NBR 6123).</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </div>
                  <span className="text-sm text-muted-foreground">{phiStruct.toFixed(2)}</span>
                </div>
                <Slider value={[phiStruct]} min={0.1} max={0.6} step={0.05} onValueChange={v => setPhiStruct(v[0])} />
              </div>
            </div>
          </div>

          <div>
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-medium">Tubulações (Bloqueio)</h3>
              <Button variant="outline" size="sm" onClick={addPipe} className="h-7 text-xs">
                <Plus className="w-3 h-3 mr-1" /> Adicionar
              </Button>
            </div>
            
            {pipes.length === 0 ? (
              <div className="text-center p-4 border border-dashed rounded-lg text-sm text-muted-foreground">
                Nenhuma tubulação adicionada.
              </div>
            ) : (
              <div className="space-y-2">
                {pipes.map((pipe, index) => (
                  <div key={pipe.id} className="flex items-center gap-2 p-2 rounded-md border bg-muted/20">
                    <label className="w-20 text-xs text-muted-foreground shrink-0">Tubo {index + 1}</label>
                    <Input
                      type="number"
                      value={pipe.diameter}
                      onChange={(e) => updatePipe(pipe.id, Number(e.target.value))}
                      step={0.1}
                      min={0.1}
                      className="h-7 text-xs font-mono"
                    />
                    <span className="text-xs text-muted-foreground">m</span>
                    <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive shrink-0" onClick={() => removePipe(pipe.id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Coluna Central: 3D */}
        <div className="flex-1 flex flex-col min-h-[500px] lg:min-h-0 bg-background rounded-xl border border-border shadow-sm overflow-hidden relative">
          <div className="absolute top-4 right-4 z-10">
            <EducationalManual type="piperack" params={{ numFrames, phiTotal: result.phiTotal }} />
          </div>
          <Piperack3D
            width={width}
            height={height}
            elevation={elevation}
            spacing={spacing}
            numFrames={numFrames}
            pipes={pipes}
            phiTotal={result.phiTotal}
            eta={result.eta}
          />
        </div>

        {/* Coluna Direita: Resultados */}
        <div className="w-full lg:w-96 shrink-0 flex flex-col gap-4 overflow-y-auto pb-8 lg:pb-0">
          <Card className="shadow-sm border-border">
            <CardHeader className="pb-4">
              <CardTitle className="text-base flex items-center justify-between">
                Forças Calculadas
                <Badge variant="secondary" className="font-mono">{result.globalForce.toFixed(1)} kN (Global)</Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 text-sm">
              <div className="flex justify-between items-center pb-2 border-b">
                <span className="text-muted-foreground">φ efetivo</span>
                <span className="font-mono font-medium">{result.phiTotal.toFixed(2)}</span>
              </div>
              <div className="flex justify-between items-center pb-2 border-b">
                <span className="text-muted-foreground">Ca frontal (Tab. 26 adaptada)</span>
                <span className="font-mono font-medium">{result.caFrontal.toFixed(2)}</span>
              </div>
              <div className="flex justify-between items-center pb-2 border-b">
                <span className="text-muted-foreground">Fator η (Tab. 28)</span>
                <span className="font-mono font-medium">{result.eta.toFixed(2)}</span>
              </div>
              <div className="flex justify-between items-center pb-2 border-b">
                <span className="text-muted-foreground text-primary font-medium">Carga Pórtico 1</span>
                <span className="font-mono font-bold text-primary">{result.linearLoadFront.toFixed(2)} kN/m</span>
              </div>
              <div className="flex justify-between items-center pb-4 border-b">
                <span className="text-muted-foreground text-primary font-medium">Carga Pórticos {numFrames > 1 ? `2 a ${numFrames}` : '-'}</span>
                <span className="font-mono font-bold text-primary">{result.linearLoadBack.toFixed(2)} kN/m</span>
              </div>
                
              <div className="pt-2">
                <h4 className="font-semibold text-sm mb-3">Distribuição do Vento (Vista Lateral)</h4>
                <div className="bg-muted/30 p-3 rounded-md border text-xs space-y-4">
                  
                  <svg width="100%" height="150" viewBox="0 0 300 150" className="bg-white rounded border">
                    {/* Linha do chão */}
                    <line x1="20" y1="110" x2="280" y2="110" stroke="#cbd5e1" strokeWidth="2" />
                    
                    {/* Renderização Dinâmica baseada no numFrames */}
                    {(() => {
                      const startX = 60;
                      const endX = 240;
                      const step = numFrames > 1 ? (endX - startX) / (numFrames - 1) : 0;
                      
                      return (
                        <>
                          {/* Vigas Longitudinais */}
                          {numFrames > 1 && (
                            <>
                              <line x1={startX + 4} y1="40" x2={endX + 4} y2="40" stroke="#94a3b8" strokeWidth="4" />
                              <line x1={startX + 4} y1="65" x2={endX + 4} y2="65" stroke="#94a3b8" strokeWidth="4" />
                            </>
                          )}

                          {/* Colunas */}
                          {Array.from({ length: numFrames }).map((_, i) => {
                            const colX = numFrames === 1 ? 150 : startX + i * step;
                            
                            return (
                              <g key={`col-${i}`}>
                                <rect x={colX} y="35" width="8" height="75" fill="#64748b" />
                                <text x={colX + 4} y="125" textAnchor="middle" fontSize={numFrames > 3 ? "8" : "10"} fill="#475569">
                                  {`C${i + 1}`}
                                </text>
                              </g>
                            );
                          })}
                          
                          {/* Linha de cota para o espaçamento (e) entre C1 e C2 */}
                          {numFrames > 1 && (
                            <>
                              <line x1={startX + 4} y1="145" x2={startX + step + 4} y2="145" stroke="#64748b" strokeWidth="1" />
                              <line x1={startX + 4} y1="142" x2={startX + 4} y2="148" stroke="#64748b" strokeWidth="1" />
                              <line x1={startX + step + 4} y1="142" x2={startX + step + 4} y2="148" stroke="#64748b" strokeWidth="1" />
                              <text x={startX + step / 2 + 4} y="142" textAnchor="middle" fontSize="8" fill="#64748b">e = {spacing}m</text>
                            </>
                          )}
                          
                          {/* Vento batendo na primeira coluna */}
                          <line x1={numFrames === 1 ? 100 : startX - 40} y1="50" x2={numFrames === 1 ? 145 : startX - 5} y2="50" stroke="#10b981" strokeWidth="2" markerEnd="url(#arrowRight)" />
                          <text x={numFrames === 1 ? 122 : startX - 22} y="45" textAnchor="middle" fill="#10b981" fontSize="10" fontWeight="bold">Vento (F)</text>
                        </>
                      );
                    })()}

                    {/* Tubulações transversais cortadas (Círculos azuis) */}
                    <circle cx="100" cy="30" r="10" fill="#3b82f6" fillOpacity="0.8" />
                    <circle cx="130" cy="30" r="14" fill="#3b82f6" fillOpacity="0.8" />
                    <circle cx="170" cy="30" r="8" fill="#3b82f6" fillOpacity="0.8" />
                    <circle cx="200" cy="30" r="12" fill="#3b82f6" fillOpacity="0.8" />
                    
                    <defs>
                      <marker id="arrowRight" markerWidth="6" markerHeight="6" refX="6" refY="3" orient="auto">
                        <path d="M0,0 L6,3 L0,6" fill="none" stroke="#10b981" strokeWidth="1.5" />
                      </marker>
                    </defs>
                  </svg>

                  <div className="pt-2 space-y-2">
                    <div className="font-bold text-primary">Forças e Momentos Aerodinâmicos</div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-background p-3 rounded border">
                      <div className="space-y-1">
                        <div className="flex justify-between text-muted-foreground"><span>F. Frontal:</span> <span className="font-mono">{(result.linearLoadFront * width).toFixed(2)} kN</span></div>
                        {numFrames > 1 && <div className="flex justify-between text-muted-foreground"><span>F. Traseiros (Total):</span> <span className="font-mono">{((numFrames - 1) * result.linearLoadBack * width).toFixed(2)} kN</span></div>}
                      </div>
                      <div className="space-y-1">
                        <div className="flex justify-between text-primary font-medium"><span>Momento Global de Tombamento:</span></div>
                        <div className="flex justify-end font-mono font-bold text-base">{(result.linearLoadFront * width * elevation + (numFrames > 1 ? (numFrames - 1) * result.linearLoadBack * width * elevation : 0)).toFixed(2)} kN·m</div>
                      </div>
                    </div>
                    <p className="text-[10px] text-muted-foreground leading-tight text-center">
                      * O Momento Global representa a ação aerodinâmica pura. As reações reais (esforços axiais e fletores) devem ser obtidas no modelo estrutural.
                    </p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
          
          <SceneCapturePanel />
        </div>
      </div>
    </div>
  );
};

export default PiperackModule;
