"use client";

import { Scale } from "lucide-react";
import {
  PackageSpecConverter,
  SeedCountWeightConverter,
  UnitConverter,
} from "@/components/common/unit-converter";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  CATEGORY_LABELS,
  DIMENSION_LABELS,
  UNIT_DEMO_GROUPS,
  UNIT_REGISTRY,
  convertUnitValue,
  formatUnitNumber,
  getUnitsByCategory,
  type UnitCategory,
} from "@/lib/units";
import { cn } from "@/lib/utils";

function UnitRegistryTable({ category }: { category?: UnitCategory }) {
  const rows = category
    ? getUnitsByCategory(category)
    : UNIT_REGISTRY.filter((u) => u.isActive !== false);

  return (
    <div className="overflow-x-auto rounded-lg border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>代码</TableHead>
            <TableHead>符号</TableHead>
            <TableHead>中文</TableHead>
            <TableHead>维度</TableHead>
            <TableHead>基准</TableHead>
            <TableHead className="text-right">factor_to_base</TableHead>
            <TableHead>可换算</TableHead>
            <TableHead>需规格</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((u) => (
            <TableRow key={u.id}>
              <TableCell className="font-mono text-xs">{u.unitCode}</TableCell>
              <TableCell>{u.symbol}</TableCell>
              <TableCell>{u.nameZh}</TableCell>
              <TableCell className="text-xs text-muted-foreground">
                {DIMENSION_LABELS[u.dimension]}
              </TableCell>
              <TableCell className="font-mono text-xs">{u.baseUnitCode ?? "—"}</TableCell>
              <TableCell className="text-right font-mono text-xs">
                {u.factorToBase != null ? u.factorToBase : "—"}
              </TableCell>
              <TableCell>
                <Badge variant={u.isConvertible ? "default" : "secondary"}>
                  {u.isConvertible ? "是" : "否"}
                </Badge>
              </TableCell>
              <TableCell>
                <Badge variant={u.isRequiredSpec ? "destructive" : "outline"}>
                  {u.isRequiredSpec ? "是" : "否"}
                </Badge>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}

function QuickExample({
  value,
  from,
  to,
  label,
}: {
  value: number;
  from: string;
  to: string;
  label: string;
}) {
  const result = convertUnitValue(value, from, to);
  return (
    <div className="rounded-lg border bg-muted/30 px-3 py-2 text-sm">
      <span className="text-muted-foreground">{label}</span>
      {result.ok ? (
        <span className="ml-2 font-medium text-foreground">
          = {formatUnitNumber(result.value)}
        </span>
      ) : (
        <span className="ml-2 text-destructive">无法换算</span>
      )}
    </div>
  );
}

export default function UnitConverterDemoPage() {
  const categories = Object.keys(CATEGORY_LABELS) as UnitCategory[];

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <div className="rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 p-2.5">
          <Scale className="h-5 w-5 text-white" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">
            农业单位换算 UnitConverter
          </h2>
          <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">
            维度 + 基准单位 + factor_to_base；支持质量、面积、产量、农事投入、种植密度、灌溉等场景
          </p>
        </div>
      </div>

      <Card className="border-emerald-200 bg-emerald-50/40 dark:border-emerald-900 dark:bg-emerald-950/20">
        <CardHeader className="pb-3">
          <CardTitle className="text-base">换算规则摘要</CardTitle>
          <CardDescription>
            普通换算：base_value = value × factor_to_base；target = base_value / target.factor_to_base
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
          {[
            ["质量", "kg"],
            ["面积", "m²（国内可显示亩）"],
            ["长度", "m"],
            ["体积", "L"],
            ["产量", "kg/ha"],
            ["施肥/用药", "kg/ha、g/ha、L/ha"],
            ["种植密度", "plants/ha"],
            ["灌溉", "mm ↔ m³/ha"],
          ].map(([label, base]) => (
            <div
              key={label}
              className="rounded-md border border-emerald-200/60 bg-background/80 px-3 py-2 dark:border-emerald-800"
            >
              <span className="font-medium text-slate-800 dark:text-slate-100">{label}</span>
              <span className="ml-2 text-muted-foreground">→ {base}</span>
            </div>
          ))}
        </CardContent>
      </Card>

      <Tabs defaultValue="scenarios">
        <TabsList className="flex h-auto flex-wrap gap-1">
          <TabsTrigger value="scenarios">业务场景</TabsTrigger>
          <TabsTrigger value="seed">粒数 ↔ 重量</TabsTrigger>
          <TabsTrigger value="package">包装规格</TabsTrigger>
          <TabsTrigger value="registry">单位表</TabsTrigger>
        </TabsList>

        <TabsContent value="scenarios" className="mt-4 space-y-4">
          <div className="grid gap-4 lg:grid-cols-2">
            {UNIT_DEMO_GROUPS.map((group) => (
              <Card key={group.id}>
                <CardHeader className="pb-3">
                  <CardTitle className="text-base">{group.title}</CardTitle>
                  <CardDescription>{group.description}</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <UnitConverter
                    dimension={group.dimension}
                    defaultFromCode={group.defaultFrom}
                    defaultToCode={group.defaultTo}
                    defaultValue={
                      group.examples[0]?.from === group.defaultFrom
                        ? group.examples[0].value
                        : 1
                    }
                  />
                  <div className="space-y-2">
                    {"examples" in group &&
                      group.examples.map((ex) => (
                        <QuickExample
                          key={ex.label}
                          value={ex.value}
                          from={ex.from}
                          to={ex.to}
                          label={ex.label}
                        />
                      ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="seed" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">粒数与重量（需千粒重 TKW）</CardTitle>
              <CardDescription>
                SeedLot 批次维护 thousand_kernel_weight 后，才可在粒 ↔ g/kg 之间自动换算
              </CardDescription>
            </CardHeader>
            <CardContent>
              <SeedCountWeightConverter defaultTkw={25} defaultCount={10000} />
              <div className="mt-4 rounded-lg border bg-muted/30 p-3 text-sm">
                示例：千粒重 25 g，10000 粒 ={" "}
                <strong>{formatUnitNumber((10000 * 25) / 1000)} g</strong>（250 g）
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="package" className="mt-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">包装单位 × 规格</CardTitle>
              <CardDescription>
                袋、管、盒、包、瓶标记 is_required_spec = true，不可直接互转
              </CardDescription>
            </CardHeader>
            <CardContent>
              <PackageSpecConverter />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="registry" className="mt-4 space-y-4">
          <Tabs defaultValue={categories[0]}>
            <TabsList className="flex h-auto flex-wrap gap-1">
              {categories.map((cat) => (
                <TabsTrigger key={cat} value={cat}>
                  {CATEGORY_LABELS[cat]}
                </TabsTrigger>
              ))}
            </TabsList>
            {categories.map((cat) => (
              <TabsContent key={cat} value={cat} className="mt-4">
                <UnitRegistryTable category={cat} />
              </TabsContent>
            ))}
          </Tabs>
        </TabsContent>
      </Tabs>

      <p className={cn("text-xs text-muted-foreground")}>
        库路径：@/lib/units · 组件路径：@/components/common/unit-converter
      </p>
    </div>
  );
}
