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 { Calculator, Info } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

export default function CalcCaModule() {
  const { t } = useI18n();
  const [l1, setL1] = useState<number>(20);
  const [l2, setL2] = useState<number>(40);
  const [h, setH] = useState<number>(10);

  // 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="p-6 max-w-7xl mx-auto space-y-6">
      <header className="flex items-center gap-4 mb-8">
        <div className="p-3 bg-primary/10 rounded-xl">
          <Calculator className="w-8 h-8 text-primary" />
        </div>
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{t('nav_calc_ca')}</h1>
          <p className="text-muted-foreground">
            Cálculo rápido de Coeficiente de Arrasto (Ca) - NBR 6123:2023, Fig. 4 e 5.
          </p>
        </div>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Left Column: Inputs & Results */}
        <div className="lg:col-span-4 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Entrada de Dados</CardTitle>
              <CardDescription>Dimensões da edificação retangular</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="l1" className="text-sm font-medium leading-none">L₁ (Largura perpendicular ao vento - m)</label>
                <Input
                  id="l1"
                  type="number"
                  min="0.1"
                  step="0.1"
                  value={l1}
                  onChange={(e) => setL1(parseFloat(e.target.value))}
                />
              </div>
              <div className="space-y-2">
                <label htmlFor="l2" className="text-sm font-medium leading-none">L₂ (Profundidade paralela ao vento - m)</label>
                <Input
                  id="l2"
                  type="number"
                  min="0.1"
                  step="0.1"
                  value={l2}
                  onChange={(e) => setL2(parseFloat(e.target.value))}
                />
              </div>
              <div className="space-y-2">
                <label htmlFor="h" className="text-sm font-medium leading-none">H (Altura - m)</label>
                <Input
                  id="h"
                  type="number"
                  min="0.1"
                  step="0.1"
                  value={h}
                  onChange={(e) => setH(parseFloat(e.target.value))}
                />
              </div>
            </CardContent>
          </Card>

          <Card className="border-primary/50 shadow-sm bg-primary/5">
            <CardHeader className="pb-2">
              <CardTitle className="text-lg flex items-center gap-2">
                <Info className="w-5 h-5 text-primary" />
                Resultados (Ca)
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4 mt-2">
                <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>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Center Column: 3D Visualization */}
        <div className="lg:col-span-4">
          <Card className="h-full flex flex-col">
            <CardHeader className="pb-2 shrink-0">
              <CardTitle className="text-lg">Visualização 3D</CardTitle>
              <CardDescription>Proporções dinâmicas</CardDescription>
            </CardHeader>
            <CardContent className="flex-1 p-0 min-h-[400px] relative rounded-b-xl overflow-hidden bg-gradient-to-b from-muted/30 to-muted/10">
              <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="always">
                <ambientLight intensity={0.5} />
                <directionalLight position={[10, 20, 10]} intensity={1} castShadow />
                <Environment preset="city" />
                <ResizableBox3D l1={safeL1} l2={safeL2} h={safeH} />
                <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>
            </CardContent>
          </Card>
        </div>

        {/* Right Column: Chart */}
        <div className="lg:col-span-4">
          <Card className="h-full">
            <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)]">
              <DragCoefficientChart l1={safeL1} l2={safeL2} h={safeH} caLow={caLow} caHigh={caHigh} />
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
