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 { calculateCylinder, type CylinderEndType } from '@/lib/modules/cylinder';
import Cylinder3DViewer from '@/components/three/Cylinder3D';
import SceneCapturePanel from '../components/SceneCapturePanel';
import ExportMenu from '../components/ExportMenu';
import { exportGenericToPDF, type GenericPDFSection } from '../lib/export-generic-pdf';

const CylinderModule: React.FC = () => {
  const { v0, terrainCategory, structureClass, s2, vk, q, cpi: globalCpi } = useWindStore();

  const [diameter, setDiameter] = React.useState(8);
  const [height, setHeight] = React.useState(20);
  const [surface, setSurface] = React.useState<'rough' | 'smooth'>('rough');
  const [endType, setEndType] = React.useState<CylinderEndType>('closed');

  const result = useMemo(() => {
    return calculateCylinder({
      d: diameter,
      h: height,
      vk,
      surface,
      endType,
      baseCpi: globalCpi,
    });
  }, [diameter, height, vk, surface, endType, globalCpi]);

  const handleExportPDF = () => {
    const sections: GenericPDFSection[] = [
      {
        title: 'Geometria do Cilindro',
        type: 'grid',
        gridItems: [
          { label: 'Diâmetro (d)', value: `${diameter} m` },
          { label: 'Altura (h)', value: `${height} m` },
          { label: 'h/d', value: result.hOverD.toFixed(2) },
          { label: 'Tipo de Superfície', value: surface === 'rough' ? 'Rugosa' : 'Lisa' },
          { label: 'Extremidades', value: endType },
          { label: 'Reynolds (Re)', value: result.re.toExponential(2) },
          { label: 'Regime', value: result.supercritical ? 'Supercrítico' : 'Subcrítico' },
        ],
      },
      {
        title: 'Pressões na Superfície',
        type: 'table',
        tableHeaders: ['Ângulo', 'Cpe', 'p (kN/m²)'],
        tableRows: result.profile.map((p) => [
          `${p.angle}°`,
          p.cpe.toFixed(2),
          p.pressureKN_m2.toFixed(3),
        ]),
      },
      {
        title: 'Força Resultante',
        type: 'grid',
        gridItems: [
          {
            label: 'Força horizontal por unidade de altura',
            value: `${result.forcePerHeightKN_m.toFixed(2)} kN/m`,
          },
          { label: 'Nota Cpi', value: result.cpiNote },
        ],
      },
    ];
    exportGenericToPDF('Cilindros', 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">Cilindro Vertical</CardTitle>
            <CardDescription>Sec. 6.2.1 — silos, reservatórios, chaminés.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between">
                <label className="text-sm font-medium">Diâmetro (d)</label>
                <span className="font-mono text-sm text-muted-foreground">{diameter} m</span>
              </div>
              <Slider min={2} max={30} step={0.5} value={[diameter]} onValueChange={(v) => setDiameter(v[0])} />
            </div>
            <div className="space-y-3">
              <div className="flex justify-between">
                <label className="text-sm font-medium">Altura (h)</label>
                <span className="font-mono text-sm text-muted-foreground">{height} m</span>
              </div>
              <Slider min={4} max={80} step={0.5} value={[height]} onValueChange={(v) => setHeight(v[0])} />
            </div>
            <Separator />
            <div className="space-y-2">
              <label className="text-sm font-medium">Tipo de Superfície</label>
              <Select value={surface} onValueChange={(v) => setSurface(v as 'rough' | 'smooth')}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="rough">Rugosa (com saliências)</SelectItem>
                  <SelectItem value="smooth">Lisa</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">Extremidades</label>
              <Select value={endType} onValueChange={(v) => setEndType(v as CylinderEndType)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="closed">Fechado</SelectItem>
                  <SelectItem value="open-top">Topo aberto</SelectItem>
                  <SelectItem value="open-bottom">Base aberta</SelectItem>
                  <SelectItem value="open-both">Ambos abertos</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>V₀:</span><span className="font-mono">{v0} m/s</span></div>
              <div className="flex justify-between"><span>S₂ (cat. {terrainCategory}, cl. {structureClass}):</span><span className="font-mono">{s2.toFixed(3)}</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">{q.toFixed(4)} kN/m²</span></div>
              <div className="flex justify-between"><span>Reynolds Re:</span><span className="font-mono">{result.re.toLocaleString('pt-BR')}</span></div>
              <div className="flex justify-between"><span>h/d:</span><span className="font-mono">{result.hOverD.toFixed(2)}</span></div>
              <div className="flex justify-between"><span>Regime:</span><span className="font-mono">{result.supercritical ? 'supercrítico' : 'subcrítico'}</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">
            h/d = {result.hOverD.toFixed(2)}
          </Badge>
          <Badge variant="outline" className="bg-background/80 backdrop-blur-sm">
            Re = {result.re.toExponential(2)}
          </Badge>
        </div>
        <div className="w-full h-full bg-muted/20">
          <Cylinder3DViewer
            diameter={diameter}
            height={height}
            cpeProfile={result.profile}
            cpi={result.cpi}
          />
        </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">Pressões na Superfície</CardTitle>
            <CardDescription>{result.cpiNote}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr className="text-muted-foreground border-b">
                    <th className="text-left py-2">Ângulo</th>
                    <th className="text-right py-2">Cpe</th>
                    <th className="text-right py-2">p (kN/m²)</th>
                  </tr>
                </thead>
                <tbody>
                  {result.profile.map((p) => (
                    <tr key={p.angle} className="border-b last:border-0">
                      <td className="py-1 font-mono">{p.angle}°</td>
                      <td className="text-right font-mono">{p.cpe.toFixed(2)}</td>
                      <td className="text-right font-mono">{p.pressureKN_m2.toFixed(3)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Separator className="my-3" />
            <div className="flex justify-between text-sm">
              <span>Força horizontal por unidade de altura:</span>
              <Badge variant="default" className="font-mono">{result.forcePerHeightKN_m.toFixed(2)} kN/m</Badge>
            </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 CylinderModule;