import React, { useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useWindStore } from '@/store/appStore';
import { calculateVault, type VaultRegime } from '@/lib/modules/vault';
import Vault3DViewer from '@/components/three/Vault3D';
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 VaultModule: React.FC = () => {
  const { vk } = useWindStore();
  const [span, setSpan] = React.useState(20);
  const [length, setLength] = React.useState(30);
  const [rise, setRise] = React.useState(5);
  const [regime, setRegime] = React.useState<VaultRegime>('laminar-rough');
  const [localCpi, setLocalCpi] = React.useState<number>(0);

  const result = useMemo(() => calculateVault({ f: rise, l: span, b: length, vk, regime, cpi: localCpi }), [span, length, rise, vk, regime, localCpi]);

  const handleExportPDF = () => {
    const sections: GenericPDFSection[] = [
      {
        title: 'Geometria da Abóbada',
        type: 'grid',
        gridItems: [
          { label: 'Vão (ℓ)', value: `${span} m` },
          { label: 'Comprimento (b)', value: `${length} m` },
          { label: 'Flecha (f)', value: `${rise} m` },
          { label: 'f/ℓ', value: (rise / span).toFixed(2) },
          { label: 'Regime', value: regime },
          { label: 'Pressão Interna (Cpi)', value: localCpi > 0 ? `+${localCpi.toFixed(2)}` : localCpi.toFixed(2) },
        ],
      },
      {
        title: 'Coeficientes de Pressão (Cpe)',
        type: 'grid',
        gridItems: [
          {
            label: 'Vento ⊥ geratriz',
            value: Object.entries(result.windPerpendicular).map(([k, v]) => `${k}: ${(v as number).toFixed(2)}`).join(' | '),
          },
          {
            label: 'Vento ∥ geratriz',
            value: Object.entries(result.windParallel).map(([k, v]) => `${k}: ${(v as number).toFixed(2)}`).join(' | '),
          },
        ],
      },
      {
        title: 'Pressões p (kN/m²)',
        type: 'grid',
        gridItems: Object.entries(result.pressures).map(([k, v]) => ({
          label: `Zona ${k}`,
          value: v.toFixed(3),
        })),
      },
    ];
    exportGenericToPDF('Abóbada Cilíndrica', 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">Abóbada Cilíndrica</CardTitle>
            <CardDescription>Sec. 6.2.3 — galpões curvos, igrejas.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Vão (ℓ)</label><span className="font-mono text-sm">{span} m</span></div>
              <Slider min={5} max={60} step={1} value={[span]} onValueChange={(v) => setSpan(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Comprimento (b)</label><span className="font-mono text-sm">{length} m</span></div>
              <Slider min={10} max={100} step={1} value={[length]} onValueChange={(v) => setLength(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between"><label className="text-sm font-medium">Flecha (f)</label><span className="font-mono text-sm">{rise} m</span></div>
              <Slider min={1} max={Math.min(span / 2, 20)} step={0.5} value={[rise]} onValueChange={(v) => setRise(v[0])} />
            </div>
            <Separator />
            <div className="space-y-2">
              <label className="text-sm font-medium">Regime de Escoamento</label>
              <Select value={regime} onValueChange={(v) => setRegime(v as VaultRegime)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="laminar-rough">Baixa turbulência (Tab. 15-17)</SelectItem>
                  <SelectItem value="turbulent-51">Turbulento — Série 51 (Tab. 18-20)</SelectItem>
                  <SelectItem value="turbulent-52">Turbulento — Série 52 (Tab. 18-20)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">Aberturas e Permeabilidade (Cpi)</label>
              <Select value={localCpi.toString()} onValueChange={(v) => setLocalCpi(Number(v))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">Fechada / Igual (Cpi = 0,0)</SelectItem>
                  <SelectItem value="0.2">Aberturas opostas — 0° (Cpi = +0,2)</SelectItem>
                  <SelectItem value="-0.3">Aberturas opostas — 90° (Cpi = -0,3)</SelectItem>
                  <SelectItem value="0.5">Abertura dominante a barlavento (Cpi = +0,5)</SelectItem>
                  <SelectItem value="0.8">Abertura quase total a barlavento (Cpi = +0,8)</SelectItem>
                  <SelectItem value="-0.5">Abertura dominante a sotavento (Cpi = -0,5)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="rounded-md border bg-muted/40 p-3 text-xs space-y-1">
              <div className="flex justify-between"><span>f/ℓ:</span><span className="font-mono">{(rise / span).toFixed(2)}</span></div>
              <div className="flex justify-between"><span>Vₖ:</span><span className="font-mono">{vk.toFixed(2)} m/s</span></div>
              <div className="flex justify-between"><span>q:</span><span className="font-mono">{result.q.toFixed(4)} kN/m²</span></div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Coluna Central: Viewer 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">f/ℓ = {(rise / span).toFixed(2)}</Badge>
          <Badge variant="outline" className={localCpi > 0 ? 'bg-destructive/10 text-destructive border-destructive/20 backdrop-blur-sm' : 'bg-background/80 backdrop-blur-sm'}>
            Cpi = {localCpi > 0 ? `+${localCpi.toFixed(2)}` : localCpi.toFixed(2)}
          </Badge>
        </div>
        <div className="absolute top-4 right-4 z-10">
          <EducationalManual type="vault" params={{ rise, span, regime, localCpi }} />
        </div>
        <div className="w-full h-full bg-muted/20">
          <Vault3DViewer span={span} length={length} rise={rise} cpi={localCpi} cpeProfile={{ ...result.windPerpendicular }} />
        </div>
      </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">Coeficientes e Pressões</CardTitle>
            <CardDescription>Vento ⊥ geratriz / ∥ geratriz</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div>
              <h4 className="text-xs font-semibold uppercase text-muted-foreground mb-2">Vento ⊥ geratriz</h4>
              <div className="grid grid-cols-3 gap-1 text-xs">
                {Object.entries(result.windPerpendicular).map(([k, v]) => (
                  <div key={k} className="rounded border bg-muted/40 p-1.5 text-center">
                    <div className="text-muted-foreground text-[10px]">{k}</div>
                    <div className="font-mono font-medium">{(v as number).toFixed(2)}</div>
                  </div>
                ))}
              </div>
            </div>
            <Separator />
            <div>
              <h4 className="text-xs font-semibold uppercase text-muted-foreground mb-2">Vento ∥ geratriz</h4>
              <div className="grid grid-cols-4 gap-1 text-xs">
                {Object.entries(result.windParallel).map(([k, v]) => (
                  <div key={k} className="rounded border bg-muted/40 p-1.5 text-center">
                    <div className="text-muted-foreground text-[10px]">{k}</div>
                    <div className="font-mono font-medium">{(v as number).toFixed(2)}</div>
                  </div>
                ))}
              </div>
            </div>
            <Separator />
            <div>
              <h4 className="text-xs font-semibold uppercase text-muted-foreground mb-2">Pressões p (kN/m²)</h4>
              <div className="grid grid-cols-3 gap-1 text-xs">
                {Object.entries(result.pressures).map(([k, v]) => (
                  <div key={k} className="rounded border bg-muted/40 p-1.5 text-center">
                    <div className="text-muted-foreground text-[10px]">{k}</div>
                    <div className="font-mono font-medium">{v.toFixed(3)}</div>
                  </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 VaultModule;