import React, { useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Input } from '@/components/ui/input';
import { useWindStore } from '@/store/appStore';
import { classifyBridge, calculateBridgeDeckForces, flutterCheck, gallopingCheck } from '@/lib/modules/bridge';
import Bridge3DViewer from '@/components/three/Bridge3D';
import SceneCapturePanel from '../components/SceneCapturePanel';
import ExportMenu from '../components/ExportMenu';
import { EducationalManual } from '@/components/EducationalManual';
import { exportGenericToPDF, type GenericPDFSection } from '../lib/export-generic-pdf';

const BridgeModule: React.FC = () => {
  const { v0, s1, terrainCategory, q } = useWindStore();
  const [lp, setLp] = React.useState(120);
  const [width, setWidth] = React.useState(14);
  const [deckHeight, setDeckHeight] = React.useState(15);
  const [heg, setHeg] = React.useState(2.5);
  const [mass, setMass] = React.useState(18000);
  const [fv, setFv] = React.useState(0.6);
  const [vk, setVk] = React.useState(45);
  const [alpha, setAlpha] = React.useState(0);
  const [vf, setVf] = React.useState(100); // Velocidade crítica de flutter da seção

  const classification = useMemo(
    () => classifyBridge({ lp, width, massPerLength: mass, fv, v0, s1, deckHeight, category: terrainCategory }),
    [lp, width, mass, fv, v0, s1, deckHeight, terrainCategory],
  );

  const forces = useMemo(() => calculateBridgeDeckForces({ width, heg: heg, vk, q, alpha }), [width, heg, vk, q, alpha]);

  const flutter = useMemo(() => flutterCheck(vf, vk), [vf, vk]);
  const galope = useMemo(() => gallopingCheck(vf, vk), [vf, vk]);

  const classColors: Record<1 | 2 | 3, string> = {
    1: 'bg-green-100 text-green-700 border-green-300',
    2: 'bg-yellow-100 text-yellow-700 border-yellow-300',
    3: 'bg-red-100 text-red-700 border-red-300',
  };

  const handleExportPDF = () => {
    const sections: GenericPDFSection[] = [
      {
        title: 'Parâmetros da Ponte',
        type: 'grid',
        gridItems: [
          { label: 'Maior vão (Lₚ)', value: `${lp} m` },
          { label: 'Largura (B)', value: `${width} m` },
          { label: 'Altura equivalente (Hₑg)', value: `${heg} m` },
          { label: 'Altura do tabuleiro (z)', value: `${deckHeight} m` },
          { label: 'Massa linear (m)', value: `${mass} kg/m` },
          { label: 'Velocidade crítica (V_it)', value: `${classification.vit.toFixed(2)} m/s` },
          { label: 'Ângulo de Ataque (α)', value: `${alpha}°` },
        ],
      },
      {
        title: 'Classificação (Pₛₑ)',
        type: 'grid',
        gridItems: [
          { label: 'Classe', value: `Classe ${classification.bridgeClass}` },
          { label: 'Pₛₑ', value: classification.pse.toFixed(4) },
          { label: 'Ação sugerida', value: classification.description },
        ],
      },
      {
        title: 'Forças no Tabuleiro',
        type: 'grid',
        gridItems: [
          { label: 'Cx / Cz / Cm', value: `${forces.cx.toFixed(2)} / ${forces.cz.toFixed(2)} / ${forces.cm.toFixed(2)}` },
          { label: 'Fx (kN/m)', value: forces.fxPerLength.toFixed(3) },
          { label: 'Fz (kN/m)', value: forces.fzPerLength.toFixed(3) },
          { label: 'Mt (kNm/m)', value: forces.fmPerLength.toFixed(3) },
        ],
      },
      {
        title: 'Verificações de Estabilidade',
        type: 'grid',
        gridItems: [
          { label: 'Flutter (V_F vs 2Vk)', value: `${flutter.vf.toFixed(1)} > ${flutter.vkCrit.toFixed(1)} m/s → ${flutter.ok ? 'OK' : 'REVER'}` },
          { label: 'Galope (V_F vs 1.25Vk)', value: `${galope.vf.toFixed(1)} > ${galope.vkCrit.toFixed(1)} m/s → ${galope.ok ? 'OK' : 'REVER'}` },
        ],
      },
    ];
    exportGenericToPDF('Tabuleiro de Ponte', sections);
  };

  return (
    <div className="flex flex-col lg:flex-row h-full w-full gap-4 p-4 lg:p-6 bg-muted/30">
      {/* Coluna Esquerda: Controles */}
      <div className="w-full lg:w-80 shrink-0 flex flex-col gap-4 overflow-y-auto pb-8 lg:pb-0">
        <Card className="shadow-sm border-border">
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">Tabuleiro de Ponte</CardTitle>
            <CardDescription>Sec. 11.2 / 11.3 — análise estática.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Maior vão (Lₚ)</label><span className="font-mono text-sm">{lp} m</span></div>
              <Slider min={20} max={500} step={5} value={[lp]} onValueChange={(v) => setLp(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Largura (B)</label><span className="font-mono text-sm">{width} m</span></div>
              <Slider min={5} max={30} step={0.5} value={[width]} onValueChange={(v) => setWidth(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Altura equivalente (Hₑg)</label><span className="font-mono text-sm">{heg} m</span></div>
              <Slider min={0.5} max={5} step={0.1} value={[heg]} onValueChange={(v) => setHeg(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Altura do tabuleiro (z)</label><span className="font-mono text-sm">{deckHeight} m</span></div>
              <Slider min={5} max={80} step={1} value={[deckHeight]} onValueChange={(v) => setDeckHeight(v[0])} />
            </div>
            <Separator />
            <div className="space-y-3">
              <label className="text-sm font-medium">m (kg/m)</label>
              <Input type="number" value={mass} onChange={(e) => setMass(Number(e.target.value))} />
            </div>
            <div className="space-y-3">
              <label className="text-sm font-medium">fᵥ (Hz)</label>
              <Input type="number" step="0.01" value={fv} onChange={(e) => setFv(Number(e.target.value))} />
            </div>
            <div className="space-y-3">
              <label className="text-sm font-medium">Vₖ(z) — projeto (m/s)</label>
              <Input type="number" value={vk} onChange={(e) => setVk(Number(e.target.value))} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Ângulo de ataque (α)</label><span className="font-mono text-sm">{alpha}°</span></div>
              <Slider min={-5} max={5} step={0.5} value={[alpha]} onValueChange={(v) => setAlpha(v[0])} />
            </div>
            <Separator />
            <div className="space-y-3">
              <label className="text-sm font-medium">Velocidade Crítica (V_F) aerodinâmica (m/s)</label>
              <Input type="number" value={vf} onChange={(e) => setVf(Number(e.target.value))} />
            </div>
            <div className="rounded-md border bg-muted/40 p-3 text-xs space-y-1">
              <div className="flex justify-between"><span>Categoria:</span><span className="font-mono">{terrainCategory}</span></div>
              <div className="flex justify-between"><span>V₀:</span><span className="font-mono">{v0} m/s</span></div>
            </div>
          </CardContent>
        </Card>
      </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 left-4 z-10 flex gap-2">
          <Badge variant="secondary" className="bg-background/80 backdrop-blur-sm">Pₛₑ = {classification.pse.toFixed(3)}</Badge>
          <Badge variant="outline" className={`bg-background/80 ${classColors[classification.bridgeClass]}`}>
            Classe {classification.bridgeClass}
          </Badge>
        </div>
        <div className="absolute top-4 right-4 z-10">
          <EducationalManual type="bridge" params={{ alpha }} />
        </div>
        <Bridge3DViewer
          lp={lp}
          width={width}
          deckHeight={deckHeight}
          heg={heg}
          cx={forces.cx}
          cz={forces.cz}
          fxPerLength={forces.fxPerLength}
          fzPerLength={forces.fzPerLength}
          alpha={alpha}
        />
      </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-3">
            <CardTitle className="text-lg">Classificação</CardTitle>
            <CardDescription>Parâmetro Pₛₑ (sec. 11.2.2)</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className={`rounded-md border-2 p-3 text-center ${classColors[classification.bridgeClass]}`}>
              <div className="text-xs font-medium">Classe {classification.bridgeClass}</div>
              <div className="font-mono text-2xl font-bold">Pₛₑ = {classification.pse.toFixed(4)}</div>
            </div>
            <p className="text-xs text-muted-foreground">{classification.description}</p>
            <Separator />
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">V_it (m/s)</div>
                <div className="font-mono font-medium">{classification.vit.toFixed(2)}</div>
              </div>
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">q (kN/m²)</div>
                <div className="font-mono font-medium">{q.toFixed(4)}</div>
              </div>
            </div>
            <Separator />
            <div className="text-xs font-semibold uppercase text-muted-foreground mb-2">Forças e Momentos no Tabuleiro (sec. 11.3)</div>
            <div className="grid grid-cols-3 gap-2 text-sm">
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Cx</div>
                <div className="font-mono font-medium">{forces.cx.toFixed(3)}</div>
              </div>
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Cz</div>
                <div className="font-mono font-medium">{forces.cz.toFixed(3)}</div>
              </div>
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Cm</div>
                <div className="font-mono font-medium">{forces.cm.toFixed(3)}</div>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-2 text-sm mt-2">
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Fx (kN/m)</div>
                <div className="font-mono font-medium">{forces.fxPerLength.toFixed(3)}</div>
              </div>
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Fz (kN/m)</div>
                <div className="font-mono font-medium">{forces.fzPerLength.toFixed(3)}</div>
              </div>
              <div className="rounded-md border bg-muted/40 p-2 text-center">
                <div className="text-[10px] text-muted-foreground">Mt (kNm/m)</div>
                <div className="font-mono font-medium">{forces.fmPerLength.toFixed(3)}</div>
              </div>
            </div>
            <Separator />
            <div className="text-xs font-semibold uppercase text-muted-foreground mb-2">Verificações de estabilidade</div>
            <div className="space-y-2">
              <div className="flex flex-col gap-1 text-xs">
                <div className="flex justify-between items-center">
                  <span>Flutter (11.5.4):</span>
                  <Badge variant={flutter.ok ? 'default' : 'destructive'}>{flutter.ok ? 'OK' : 'REVER'}</Badge>
                </div>
                <div className="text-muted-foreground ml-1">
                  V_F = {flutter.vf.toFixed(1)} {flutter.ok ? '>' : '<'} 2.0·Vₖ = {flutter.vkCrit.toFixed(1)} m/s
                </div>
              </div>
              <div className="flex flex-col gap-1 text-xs">
                <div className="flex justify-between items-center">
                  <span>Galope (11.5.6):</span>
                  <Badge variant={galope.ok ? 'default' : 'destructive'}>{galope.ok ? 'OK' : 'REVER'}</Badge>
                </div>
                <div className="text-muted-foreground ml-1">
                  V_F = {galope.vf.toFixed(1)} {galope.ok ? '>' : '<'} 1.25·Vₖ = {galope.vkCrit.toFixed(1)} m/s
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <div className="flex justify-center bg-background rounded-xl border border-border shadow-sm p-4">
          <ExportMenu onExportPDF={handleExportPDF} />
        </div>
        
        <SceneCapturePanel />
      </div>
    </div>
  );
};

export default BridgeModule;