import React, { useState, useMemo } from 'react';
import { useGalpaoStore } from '../store/galpaoStore';
import { useWindStore } from '../store/appStore';
import { useI18n } from '../store/i18nStore';
import {
  getColumnLinearLoads,
  getRoofLinearLoads,
  getAllPillarBaseReactions,
  getPillarBaseMoment,
  getDragForce,
} from '../lib/line-loads';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from './ui/card';
import { Input } from './ui/input';
import { Badge } from './ui/badge';
import { Separator } from './ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Calculator, Layers, ChevronRight } from 'lucide-react';

const LinearLoadsTable: React.FC = () => {
  const galpao = useGalpaoStore();
  const wind = useWindStore();
  const { t } = useI18n();
  const { width: b, length: a, height: h, roofPitch, wallCpe, roofCpe } = galpao;
  const { q, cpi, windAngle } = wind;

  const [frameSpacing, setFrameSpacing] = useState<number>(6.0);
  const [purlinSpacing, setPurlinSpacing] = useState<number>(1.5);

  const columnLoads = useMemo(
    () => getColumnLinearLoads(cpi, q, wallCpe, frameSpacing, windAngle),
    [cpi, q, wallCpe, frameSpacing, windAngle],
  );

  const roofLoads = useMemo(
    () => getRoofLinearLoads(cpi, q, roofCpe, purlinSpacing, roofPitch),
    [cpi, q, roofCpe, purlinSpacing, roofPitch],
  );

  const reactions = useMemo(
    () => getAllPillarBaseReactions(columnLoads, h),
    [columnLoads, h],
  );

  const drag = useMemo(
    () => getDragForce(wallCpe, roofCpe, q, a, b, h, roofPitch, windAngle),
    [wallCpe, roofCpe, q, a, b, h, roofPitch, windAngle],
  );

  const fmt = (v: number, p = 3) => v.toFixed(p);
  const fmtSigned = (v: number, p = 3) => (v >= 0 ? `+${v.toFixed(p)}` : v.toFixed(p));

  return (
    <Card className="shadow-sm border-border">
      <CardHeader className="pb-3">
        <CardTitle className="text-lg flex items-center gap-2">
          <Calculator className="w-5 h-5 text-primary" />
          {t('linear_loads_title')}
        </CardTitle>
        <CardDescription>{t('linear_loads_desc')}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="space-y-1">
            <label className="text-xs font-medium text-foreground">
              {t('linear_loads_frame_spacing')}
            </label>
            <Input
              type="number"
              min={3}
              max={15}
              step={0.5}
              value={frameSpacing}
              onChange={(e) => setFrameSpacing(Number(e.target.value))}
            />
            <p className="text-[10px] text-muted-foreground">{t('linear_loads_frame_help')}</p>
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium text-foreground">
              {t('linear_loads_purlin_spacing')}
            </label>
            <Input
              type="number"
              min={0.5}
              max={3}
              step={0.1}
              value={purlinSpacing}
              onChange={(e) => setPurlinSpacing(Number(e.target.value))}
            />
            <p className="text-[10px] text-muted-foreground">{t('linear_loads_purlin_help')}</p>
          </div>
        </div>

        <Separator />

        <Tabs defaultValue="pilares" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="pilares">{t('linear_loads_tab_pillars')}</TabsTrigger>
            <TabsTrigger value="tercas">{t('linear_loads_tab_purlins')}</TabsTrigger>
            <TabsTrigger value="reacoes">{t('linear_loads_tab_reactions')}</TabsTrigger>
          </TabsList>

          <TabsContent value="pilares" className="space-y-3">
            <div className="rounded-md border overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-muted/40">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Pilar</th>
                    <th className="px-3 py-2 text-right font-medium">Cpe</th>
                    <th className="px-3 py-2 text-right font-medium">q · (Cpe − Cpi) [kN/m²]</th>
                    <th className="px-3 py-2 text-right font-medium">w [kN/m]</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { label: t('linear_loads_pillar_windward'), cpe: windAngle === 0 ? wallCpe.C : wallCpe.A, w: columnLoads.windward },
                    { label: t('linear_loads_pillar_leeward'), cpe: windAngle === 0 ? wallCpe.D : wallCpe.B, w: columnLoads.leeward },
                    { label: t('linear_loads_pillar_side1'), cpe: windAngle === 0 ? wallCpe.A : wallCpe.C, w: columnLoads.sideA },
                    { label: t('linear_loads_pillar_side2'), cpe: windAngle === 0 ? wallCpe.B : wallCpe.D, w: columnLoads.sideB },
                  ].map((row) => (
                    <tr key={row.label} className="border-t">
                      <td className="px-3 py-2 font-medium">{row.label}</td>
                      <td className="px-3 py-2 text-right font-mono">{fmt(row.cpe, 2)}</td>
                      <td className="px-3 py-2 text-right font-mono">{fmt(q * (row.cpe - cpi), 3)}</td>
                      <td className="px-3 py-2 text-right font-mono font-semibold">
                        {fmtSigned(row.w)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <p className="text-[11px] text-muted-foreground leading-relaxed">
              <ChevronRight className="w-3 h-3 inline -mt-0.5" /> {t('linear_loads_sign_positive')}
            </p>
          </TabsContent>

          <TabsContent value="tercas" className="space-y-3">
            <div className="rounded-md border overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-muted/40">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Zona</th>
                    <th className="px-3 py-2 text-right font-medium">Cpe</th>
                    <th className="px-3 py-2 text-right font-medium">w [kN/m]</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { zona: 'E', cpe: roofCpe.E, w: roofLoads.E },
                    { zona: 'F', cpe: roofCpe.F, w: roofLoads.F },
                    { zona: 'G', cpe: roofCpe.G, w: roofLoads.G },
                    { zona: 'H', cpe: roofCpe.H, w: roofLoads.H },
                    { zona: 'I', cpe: roofCpe.I, w: roofLoads.I },
                    { zona: 'J', cpe: roofCpe.J, w: roofLoads.J },
                  ].map((row) => (
                    <tr key={row.zona} className="border-t">
                      <td className="px-3 py-2 font-mono font-semibold">{row.zona}</td>
                      <td className="px-3 py-2 text-right font-mono">{fmt(row.cpe, 2)}</td>
                      <td className="px-3 py-2 text-right font-mono font-semibold">
                        {fmtSigned(row.w)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <p className="text-[11px] text-muted-foreground leading-relaxed">
              <Layers className="w-3 h-3 inline -mt-0.5" /> {t('linear_loads_purlin_apply')}
            </p>
          </TabsContent>

          <TabsContent value="reacoes" className="space-y-3">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center">
              {[
                { label: t('linear_loads_pillar_windward'), v: reactions.windward, m: getPillarBaseMoment(columnLoads.windward, h) },
                { label: t('linear_loads_pillar_leeward'), v: reactions.leeward, m: getPillarBaseMoment(columnLoads.leeward, h) },
                { label: t('linear_loads_pillar_side1'), v: reactions.sideA, m: getPillarBaseMoment(columnLoads.sideA, h) },
                { label: t('linear_loads_pillar_side2'), v: reactions.sideB, m: getPillarBaseMoment(columnLoads.sideB, h) },
              ].map((r) => (
                <div key={r.label} className="rounded-md border bg-muted/30 p-3">
                  <div className="text-[10px] uppercase tracking-wider text-muted-foreground">{r.label}</div>
                  <div className="font-mono text-base font-semibold">{fmtSigned(r.v, 2)} kN</div>
                  <div className="font-mono text-[11px] text-muted-foreground">M = {fmtSigned(r.m, 2)} kN·m</div>
                </div>
              ))}
            </div>
            <Separator />
            <div className="rounded-md border bg-muted/40 p-3 space-y-1">
              <div className="flex justify-between text-sm">
                <span className="font-medium">{t('linear_loads_total_reaction')}:</span>
                <span className="font-mono font-semibold">{fmtSigned(reactions.total, 2)} kN</span>
              </div>
              <div className="flex justify-between text-sm">
                <span>Força de arrasto global estimada:</span>
                <span className="font-mono">{fmt(drag.forceKN, 2)} kN</span>
              </div>
              <div className="flex justify-between text-sm">
                <span>Cₐ efetivo (F/q·A_frente):</span>
                <span className="font-mono">{fmt(drag.caEfetivo, 3)}</span>
              </div>
            </div>
            <p className="text-[11px] text-muted-foreground leading-relaxed">
              {t('linear_loads_warning_simplified')}
            </p>
          </TabsContent>
        </Tabs>

        <Separator />

        <div className="flex flex-wrap gap-2 text-xs">
          <Badge variant="secondary" className="font-mono">
            q = {fmt(q, 4)} kN/m²
          </Badge>
          <Badge variant="secondary" className="font-mono">
            Cpi = {fmtSigned(cpi, 2)}
          </Badge>
          <Badge variant="secondary" className="font-mono">
            h = {fmt(h, 2)} m
          </Badge>
          <Badge variant="secondary" className="font-mono">
            θ = {fmt(roofPitch, 0)}°
          </Badge>
        </div>
      </CardContent>
    </Card>
  );
};

export default LinearLoadsTable;