import { useState, useMemo } from 'react';
import { useWindStore } from '@/store/appStore';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Slider } from '@/components/ui/slider';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { searchStations } from '@/lib/stations-lookup';
import type { PermeabilityCase } from '@/lib/internal-pressure';
import { Settings2 } from 'lucide-react';
import { Button } from '@/components/ui/button';

export function GlobalWindSettingsModal() {
  const {
    v0,
    s1,
    s3,
    s3Group,
    terrainCategory,
    structureClass,
    s2,
    vk,
    q,
    permeabilityCase,
    cpiRatio,
    cpi,
    setV0,
    setS1,
    setS3,
    setS3Group,
    setTerrainCategory,
    setPermeabilityCase,
    setCpiRatio,
  } = useWindStore();

  const [stationQuery, setStationQuery] = useState('');
  const filteredStations = useMemo(() => searchStations(stationQuery), [stationQuery]);

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="gap-2 bg-background shadow-sm hover:bg-muted/50 border-primary/20 text-primary">
          <Settings2 className="w-4 h-4" />
          <span className="hidden sm:inline">Parâmetros do Vento</span>
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Configurações Globais</DialogTitle>
          <DialogDescription>
            Defina os parâmetros do vento que afetam todas as estruturas do projeto.
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue="norma" className="w-full mt-2">
          <TabsList className="grid w-full grid-cols-3 mb-4">
            <TabsTrigger value="norma">NBR 6123</TabsTrigger>
            <TabsTrigger value="cpi">Cpi</TabsTrigger>
            <TabsTrigger value="local">Local</TabsTrigger>
          </TabsList>

          <TabsContent value="norma" className="space-y-6">
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <label className="text-sm font-medium text-foreground">Velocidade Básica (V₀)</label>
                <span className="text-sm text-muted-foreground font-mono">{v0} m/s</span>
              </div>
              <Slider min={25} max={55} step={1} value={[v0]} onValueChange={(vals) => setV0(vals[0])} className="py-1 cursor-pointer" />
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Fator Topográfico (S₁)</label>
              <Select value={s1.toString()} onValueChange={(val) => setS1(Number(val))}>
                <SelectTrigger className="w-full"><SelectValue placeholder="S₁" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="0.9">0,9 (Vale profundo protegido)</SelectItem>
                  <SelectItem value="1">1,0 (Terreno plano)</SelectItem>
                  <SelectItem value="1.1">1,1 (Talude)</SelectItem>
                  <SelectItem value="1.2">1,2 (Morro)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Categoria do Terreno (S₂)</label>
              <Select value={terrainCategory} onValueChange={(val) => setTerrainCategory(val as typeof terrainCategory)}>
                <SelectTrigger className="w-full"><SelectValue placeholder="Categoria" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="I">I — Superfícies lisas (Mar calmo, lagos, rios)</SelectItem>
                  <SelectItem value="II">II — Terrenos abertos em nível (Campos, pastos)</SelectItem>
                  <SelectItem value="III">III — Terrenos planos/ondulados c/ obstáculos (Granjas, subúrbios rurais)</SelectItem>
                  <SelectItem value="IV">IV — Obstáculos numerosos e próximos (Cidades pequenas/médias)</SelectItem>
                  <SelectItem value="V">V — Obstáculos numerosos e altos (Grandes cidades, centros industriais)</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>Classe (maior dimensão):</span><span className="font-mono font-medium">{structureClass}</span></div>
              <div className="flex justify-between"><span>S₂:</span><span className="font-mono font-medium">{s2.toFixed(3)}</span></div>
              <div className="flex justify-between"><span>Vₖ:</span><span className="font-mono font-medium">{vk.toFixed(2)} m/s</span></div>
              <div className="flex justify-between"><span>q:</span><span className="font-mono font-medium">{q.toFixed(4)} kN/m²</span></div>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Grupo Estatístico (S₃)</label>
              <Select value={s3Group.toString()} onValueChange={(val) => setS3Group(Number(val) as 1 | 2 | 3 | 4 | 5)}>
                <SelectTrigger className="w-full"><SelectValue placeholder="Grupo" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Grupo 1 — Risco à vida (Hospitais, quartéis) (S₃=1,11)</SelectItem>
                  <SelectItem value="2">Grupo 2 — Edificações comuns (Hotéis, residências) (S₃=1,06)</SelectItem>
                  <SelectItem value="3">Grupo 3 — Edificações de baixo risco (Comércio, indústrias) (S₃=1,00)</SelectItem>
                  <SelectItem value="4">Grupo 4 — Baixo fator humano (Silos, depósitos) (S₃=0,95)</SelectItem>
                  <SelectItem value="5">Grupo 5 — Estruturas temporárias (S₃=0,83)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <label className="text-sm font-medium text-foreground">S₃ customizado</label>
                <span className="text-sm text-muted-foreground font-mono">{s3.toFixed(2)}</span>
              </div>
              <Slider min={0.83} max={1.10} step={0.01} value={[s3]} onValueChange={(vals) => setS3(vals[0])} className="py-1 cursor-pointer" />
            </div>
          </TabsContent>

          <TabsContent value="cpi" className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium text-foreground">Caso de Permeabilidade</label>
              <Select value={permeabilityCase} onValueChange={(val) => setPermeabilityCase(val as PermeabilityCase)}>
                <SelectTrigger className="w-full"><SelectValue placeholder="Selecione" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="two-opposite-permeable">Duas faces opostas permeáveis</SelectItem>
                  <SelectItem value="four-equally-permeable">Quatro faces igualmente permeáveis</SelectItem>
                  <SelectItem value="dominant-windward">Abertura dominante — barlavento</SelectItem>
                  <SelectItem value="dominant-leeward">Abertura dominante — sotavento</SelectItem>
                  <SelectItem value="dominant-lateral">Abertura dominante — lateral</SelectItem>
                  <SelectItem value="airtight">Edificação estanque</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {(permeabilityCase === 'dominant-windward' || permeabilityCase === 'dominant-lateral') && (
              <div className="space-y-3 mt-4">
                <div className="flex justify-between items-center">
                  <label className="text-sm font-medium text-foreground">Razão de áreas</label>
                  <span className="text-sm text-muted-foreground font-mono">{cpiRatio.toFixed(2)}</span>
                </div>
                <Slider min={0.1} max={5} step={0.05} value={[cpiRatio]} onValueChange={(vals) => setCpiRatio(vals[0])} className="py-1 cursor-pointer" />
                <p className="text-xs text-muted-foreground">
                  Razão entre a área da abertura dominante e a área total das demais aberturas em faces com sucção externa.
                </p>
              </div>
            )}

            <div className="rounded-md border bg-muted/40 p-3 mt-4">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium">Cpi calculado:</span>
                <Badge variant="default" className="font-mono text-base">{cpi.toFixed(2)}</Badge>
              </div>
              <p className="text-xs text-muted-foreground mt-2">
                Limitado a ±0,9 conforme norma. A pressão final usada é p = q · (Cpe − Cpi).
              </p>
            </div>
          </TabsContent>

          <TabsContent value="local" className="space-y-4">
            <div className="space-y-3">
              <Input
                placeholder="Buscar cidade ou estação..."
                value={stationQuery}
                onChange={(e) => setStationQuery(e.target.value)}
              />
              <div className="max-h-[300px] overflow-y-auto rounded-md border divide-y">
                {filteredStations.slice(0, 30).map((s) => (
                  <button
                    key={s.id}
                    onClick={() => setV0(s.v0)}
                    className="w-full text-left px-3 py-2 hover:bg-muted/60 transition-colors"
                  >
                    <div className="flex justify-between">
                      <span className="font-medium text-sm">{s.nome}</span>
                      <Badge variant="outline" className="font-mono text-xs">V₀ = {s.v0} m/s</Badge>
                    </div>
                    <div className="text-xs text-muted-foreground">{s.latitude} · {s.longitude} · {s.altitude} m</div>
                  </button>
                ))}
              </div>
              <p className="text-xs text-muted-foreground">
                Selecionar uma estação ajusta V₀. Você pode sobrescrever manualmente na aba NBR.
              </p>
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
