import { useState } from 'react';
import { getDragCoefficient } from '@/lib/drag';
import { useI18n } from '@/store/i18nStore';
import { DragCoefficientChart } from '@/components/DragCoefficientChart';
import { ResizableBox3D } from '@/components/three/ResizableBox3D';
import SceneCanvas from '@/components/SceneCanvas';
import { Environment } from '@react-three/drei';
import { ViewerOrbitControls as OrbitControls } from '@/components/three/ViewerOrbitControls';
import { EducationalManual } from '@/components/EducationalManual';
import { Wind, Box } from 'lucide-react';
import { Slider } from '@/components/ui/slider';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

export default function CalcCaModule() {
  const i18n = useI18n(); // Apenas chamando caso necessário no ciclo de vida, sem extrair 't'
  const [l1, setL1] = useState<number>(20);
  const [l2, setL2] = useState<number>(40);
  const [h, setH] = useState<number>(10);
  const [viewMode, setViewMode] = useState<'solid' | 'airflow'>('solid');

  // Clamp inputs to avoid Infinity or negative values breaking the UI
  const safeL1 = Math.max(0.1, l1 || 1);
  const safeL2 = Math.max(0.1, l2 || 1);
  const safeH = Math.max(0.1, h || 1);

  const caLow = getDragCoefficient(safeL1, safeL2, safeH, 'low');
  const caHigh = getDragCoefficient(safeL1, safeL2, safeH, 'high');

  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 flex flex-row items-start justify-between space-y-0 pr-6">
            <div>
              <CardTitle className="text-lg">Calc_Ca</CardTitle>
              <CardDescription>Cálculo rápido de Coeficiente de Arrasto (Ca)</CardDescription>
            </div>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between">
                <label className="text-sm font-medium">L₁ (Largura)</label>
                <span className="font-mono text-sm">{l1} m</span>
              </div>
              <Slider min={1} max={100} step={1} value={[l1]} onValueChange={(v) => setL1(v[0])} />
            </div>
            
            <div className="space-y-3">
              <div className="flex justify-between">
                <label className="text-sm font-medium">L₂ (Profundidade)</label>
                <span className="font-mono text-sm">{l2} m</span>
              </div>
              <Slider min={1} max={100} step={1} value={[l2]} onValueChange={(v) => setL2(v[0])} />
            </div>
            
            <div className="space-y-3">
              <div className="flex justify-between">
                <label className="text-sm font-medium">H (Altura)</label>
                <span className="font-mono text-sm">{h} m</span>
              </div>
              <Slider min={1} max={100} step={1} value={[h]} onValueChange={(v) => setH(v[0])} />
            </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 right-16 z-10">
          <div className="flex bg-background/80 backdrop-blur-sm border border-border/80 rounded-md shadow-sm p-1">
            <button
              onClick={() => setViewMode('solid')}
              className={`px-3 py-1 text-xs font-medium rounded-sm transition-colors ${viewMode === 'solid' ? 'bg-primary/20 text-primary' : 'text-muted-foreground hover:bg-muted/50'}`}
            >
              <Box className="w-3.5 h-3.5 inline-block mr-1.5" />
              Sólido
            </button>
            <button
              onClick={() => setViewMode('airflow')}
              className={`px-3 py-1 text-xs font-medium rounded-sm transition-colors ${viewMode === 'airflow' ? 'bg-primary/20 text-primary' : 'text-muted-foreground hover:bg-muted/50'}`}
            >
              <Wind className="w-3.5 h-3.5 inline-block mr-1.5" />
              Fluxo
            </button>
          </div>
        </div>
        <div className="absolute top-4 right-4 z-10">
          <EducationalManual type="calc_ca" params={{ l1: safeL1, l2: safeL2, h: safeH }} />
        </div>
        
        <SceneCanvas 
          moduleId="calc_ca" 
          camera={{ position: [50, 40, 50], fov: 45 }} 
          fallback={<div />} 
          frameloop={viewMode === 'airflow' ? 'always' : 'demand'}
        >
          <ambientLight intensity={0.5} />
          <directionalLight position={[10, 20, 10]} intensity={1} castShadow />
          <Environment preset="city" />
          <ResizableBox3D l1={safeL1} l2={safeL2} h={safeH} viewMode={viewMode} />
          <OrbitControls makeDefault minPolarAngle={0} maxPolarAngle={Math.PI / 2 - 0.1} />
        </SceneCanvas>
        
        <div className="absolute bottom-4 left-4 right-20 text-center text-xs text-muted-foreground pointer-events-none">
          Arraste para rotacionar, role para aproximar
        </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">Resultados (Ca)</CardTitle>
            <CardDescription>Valores baseados nas tabelas 4 e 5</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex justify-between items-center p-3 bg-background rounded-lg border">
              <span className="font-medium text-muted-foreground">Baixa Turbulência</span>
              <span className="text-2xl font-bold text-primary">{caLow.toFixed(2)}</span>
            </div>
            <div className="flex justify-between items-center p-3 bg-background rounded-lg border">
              <span className="font-medium text-muted-foreground">Alta Turbulência</span>
              <span className="text-2xl font-bold text-primary">{caHigh.toFixed(2)}</span>
            </div>
            <div className="text-xs text-muted-foreground flex gap-4 mt-2 px-1">
              <span>H/L₁ = {(safeH / safeL1).toFixed(2)}</span>
              <span>L₁/L₂ = {(safeL1 / safeL2).toFixed(2)}</span>
            </div>
          </CardContent>
        </Card>

        {/* Ábaco */}
        <Card className="shadow-sm border-border flex-1 min-h-[300px]">
          <CardHeader className="pb-2">
            <CardTitle className="text-lg">Ábaco NBR 6123</CardTitle>
            <CardDescription>Curvas isotermas aproximadas</CardDescription>
          </CardHeader>
          <CardContent className="flex items-center justify-center h-[calc(100%-80px)] min-h-[250px]">
            <DragCoefficientChart l1={safeL1} l2={safeL2} h={safeH} caLow={caLow} caHigh={caHigh} />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
