"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { ArrowLeftRight, Plus, RotateCcw, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "@/components/ui/pagination";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
  fetchSeedLotOptions,
  fetchSeedLotRows,
  fetchSeedLotTransactions,
  inferTransactionAction,
} from "../api";
import { TransactionActionDialog } from "./TransactionActionDialog";
import {
  NONE_SELECT_VALUE,
  TRANSACTION_ACTION_LABEL,
  type SeedLotRecord,
  type SeedLotTransactionQuery,
  type SeedLotTransactionRecord,
  type SelectOption,
  type TransactionActionType,
} from "../types";

function actionBadge(action: TransactionActionType | "unknown") {
  if (action === "unknown") {
    return <Badge variant="outline">其他</Badge>;
  }
  const className = action === "in"
    ? "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200"
    : action === "out" || action === "consume"
      ? "bg-red-50 text-red-700 dark:bg-red-400/10 dark:text-red-200"
      : "bg-sky-50 text-sky-700 dark:bg-sky-400/10 dark:text-sky-200";
  return <Badge variant="outline" className={className}>{TRANSACTION_ACTION_LABEL[action]}</Badge>;
}

const emptyQuery = (): SeedLotTransactionQuery => ({
  seed_lot_id: NONE_SELECT_VALUE,
  program_id: NONE_SELECT_VALUE,
  location_id: NONE_SELECT_VALUE,
  date_from: "",
  date_to: "",
  keyword: "",
});

interface SeedLotTransactionPanelProps {
  seedLotDbId?: string;
  embedded?: boolean;
  onChanged?: () => void;
}

export function SeedLotTransactionPanel({
  seedLotDbId,
  embedded = false,
  onChanged,
}: SeedLotTransactionPanelProps) {
  const [rows, setRows] = useState<SeedLotTransactionRecord[]>([]);
  const [seedLots, setSeedLots] = useState<SeedLotRecord[]>([]);
  const [seedLotOptions, setSeedLotOptions] = useState<SelectOption[]>([]);
  const [programOptions, setProgramOptions] = useState<SelectOption[]>([]);
  const [locationOptions, setLocationOptions] = useState<SelectOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [draftQuery, setDraftQuery] = useState<SeedLotTransactionQuery>(() => ({
    ...emptyQuery(),
    seed_lot_id: seedLotDbId ?? NONE_SELECT_VALUE,
  }));
  const [appliedQuery, setAppliedQuery] = useState<SeedLotTransactionQuery>(() => ({
    ...emptyQuery(),
    seed_lot_id: seedLotDbId ?? NONE_SELECT_VALUE,
  }));
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dialogOpen, setDialogOpen] = useState(false);

  const seedLotMap = useMemo(
    () => new Map(seedLots.map((row) => [row.id, row])),
    [seedLots],
  );

  const loadData = useCallback(async (force = false) => {
    setLoading(true);
    setError(null);
    try {
      const [options, lots, transactions] = await Promise.all([
        fetchSeedLotOptions(force),
        fetchSeedLotRows(undefined, force),
        fetchSeedLotTransactions({
          seed_lot_id: optionalQueryValue(appliedQuery.seed_lot_id),
          program_id: optionalQueryValue(appliedQuery.program_id),
          location_id: optionalQueryValue(appliedQuery.location_id),
          date_from: appliedQuery.date_from || undefined,
          date_to: appliedQuery.date_to || undefined,
          keyword: appliedQuery.keyword || undefined,
        }),
      ]);
      setSeedLotOptions(options.seedLots);
      setProgramOptions(options.programs);
      setLocationOptions(options.locations);
      setSeedLots(lots);
      setRows(transactions);
    } catch (event) {
      setError(event instanceof Error ? event.message : "交易记录加载失败");
    } finally {
      setLoading(false);
    }
  }, [appliedQuery]);

  useEffect(() => {
    let mounted = true;
    loadData().catch(() => {
      if (mounted) setLoading(false);
    });
    return () => { mounted = false; };
  }, [loadData]);

  useEffect(() => {
    if (!seedLotDbId) return;
    const locked = { ...emptyQuery(), seed_lot_id: seedLotDbId };
    setDraftQuery(locked);
    setAppliedQuery(locked);
  }, [seedLotDbId]);

  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const pagedRows = rows.slice((page - 1) * pageSize, page * pageSize);

  useEffect(() => {
    setPage(1);
  }, [appliedQuery, pageSize]);

  const handleSuccess = () => {
    void loadData(true);
    onChanged?.();
  };

  return (
    <div className="flex min-h-full flex-col">
      {!embedded ? (
        <div className="mb-5 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="flex items-center gap-3">
            <div className="rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 p-2.5">
              <ArrowLeftRight className="h-5 w-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-50">库存交易</h2>
              <p className="mt-0.5 text-sm text-slate-500 dark:text-slate-400">
                通过入库、出库、转移、分装、消耗/报废等业务动作记录 seed_lot_transaction
              </p>
            </div>
          </div>
          <Button className="shrink-0 gap-2" onClick={() => setDialogOpen(true)}>
            <Plus className="h-4 w-4" />
            新建交易
          </Button>
        </div>
      ) : (
        <div className="mb-4 flex items-center justify-between gap-3">
          <p className="text-sm text-slate-500 dark:text-slate-400">
            本批次相关流转记录（含来源/目标）；交易创建后会自动更新批次库存。
          </p>
          <Button size="sm" className="gap-2 shrink-0" onClick={() => setDialogOpen(true)}>
            <Plus className="h-4 w-4" />
            新建交易
          </Button>
        </div>
      )}

      {!embedded ? (
        <div className="mb-4 flex flex-wrap gap-2">
          <span className="rounded-full bg-cyan-50 px-3 py-1 text-xs text-cyan-700 dark:bg-cyan-400/10 dark:text-cyan-200">
            GET /brapi/v2/seedlots/transactions
          </span>
          <span className="rounded-full bg-blue-50 px-3 py-1 text-xs text-blue-700 dark:bg-blue-400/10 dark:text-blue-200">
            POST /brapi/v2/seedlots/transactions
          </span>
        </div>
      ) : null}

      <div className="mb-4 rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {!seedLotDbId ? (
            <div className="space-y-1.5">
              <Label className="text-xs text-slate-500">批次</Label>
              <Select
                value={draftQuery.seed_lot_id ?? NONE_SELECT_VALUE}
                onValueChange={(value) => setDraftQuery((current) => ({ ...current, seed_lot_id: value }))}
              >
                <SelectTrigger><SelectValue placeholder="全部批次" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value={NONE_SELECT_VALUE}>全部批次</SelectItem>
                  {seedLotOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          ) : null}
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">Program</Label>
            <Select
              value={draftQuery.program_id ?? NONE_SELECT_VALUE}
              onValueChange={(value) => setDraftQuery((current) => ({ ...current, program_id: value }))}
            >
              <SelectTrigger><SelectValue placeholder="全部 Program" /></SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE_SELECT_VALUE}>全部 Program</SelectItem>
                {programOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">Location</Label>
            <Select
              value={draftQuery.location_id ?? NONE_SELECT_VALUE}
              onValueChange={(value) => setDraftQuery((current) => ({ ...current, location_id: value }))}
            >
              <SelectTrigger><SelectValue placeholder="全部地点" /></SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE_SELECT_VALUE}>全部地点</SelectItem>
                {locationOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">开始日期</Label>
            <Input
              type="date"
              value={draftQuery.date_from ?? ""}
              onChange={(event) => setDraftQuery((current) => ({ ...current, date_from: event.target.value }))}
            />
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">结束日期</Label>
            <Input
              type="date"
              value={draftQuery.date_to ?? ""}
              onChange={(event) => setDraftQuery((current) => ({ ...current, date_to: event.target.value }))}
            />
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-slate-500">关键词</Label>
            <Input
              value={draftQuery.keyword ?? ""}
              onChange={(event) => setDraftQuery((current) => ({ ...current, keyword: event.target.value }))}
              placeholder="交易 ID、说明、批次..."
            />
          </div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          <Button type="button" variant="outline" className="gap-2" onClick={() => {
            const reset = { ...emptyQuery(), seed_lot_id: seedLotDbId ?? NONE_SELECT_VALUE };
            setDraftQuery(reset);
            setAppliedQuery(reset);
          }}>
            <RotateCcw className="h-4 w-4" />
            重置
          </Button>
          <Button type="button" className="gap-2" onClick={() => setAppliedQuery({ ...draftQuery })}>
            <Search className="h-4 w-4" />
            查询
          </Button>
        </div>
      </div>

      {error ? (
        <div className="mb-4 rounded-xl border border-destructive/20 bg-destructive/10 px-4 py-3 text-sm font-medium text-destructive">
          {error}
        </div>
      ) : null}

      <div className="min-h-0 flex-1 overflow-hidden rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-950">
        <Table>
          <TableHeader>
            <TableRow className="border-slate-200 bg-slate-50 dark:border-slate-800 dark:bg-slate-900">
              <TableHead className="w-10 text-xs font-medium text-slate-400">#</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">动作</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">来源批次</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">目标批次</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">数量</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">时间</TableHead>
              <TableHead className="text-xs font-medium text-slate-500">说明</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              Array.from({ length: 6 }).map((_, index) => (
                <TableRow key={`loading-${index}`}>
                  <TableCell><Skeleton className="h-4 w-5" /></TableCell>
                  {Array.from({ length: 6 }).map((__, cellIndex) => (
                    <TableCell key={cellIndex}><Skeleton className="h-4 w-24" /></TableCell>
                  ))}
                </TableRow>
              ))
            ) : pagedRows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="py-16 text-center text-sm text-slate-400">
                  暂无交易记录，点击「新建交易」开始录入
                </TableCell>
              </TableRow>
            ) : (
              pagedRows.map((row, index) => {
                const action = inferTransactionAction(row);
                return (
                  <TableRow key={row.id || index}>
                    <TableCell className="text-xs text-slate-400">{(page - 1) * pageSize + index + 1}</TableCell>
                    <TableCell>{actionBadge(action)}</TableCell>
                    <TableCell className="text-sm">{row.from_seed_lot_name || row.from_seed_lot_id || "—"}</TableCell>
                    <TableCell className="text-sm">{row.to_seed_lot_name || row.to_seed_lot_id || "—"}</TableCell>
                    <TableCell className="text-sm">{row.amount ?? "—"}{row.units ? ` ${row.units}` : ""}</TableCell>
                    <TableCell className="text-sm">{row.timestamp ? String(row.timestamp).slice(0, 19).replace("T", " ") : "—"}</TableCell>
                    <TableCell className="max-w-[20rem] whitespace-normal break-words text-sm">{row.description || "—"}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

      <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <p className="text-xs text-slate-400">共 {rows.length} 条记录，第 {page}/{totalPages} 页</p>
        <div className="flex items-center gap-3">
          <Select value={String(pageSize)} onValueChange={(value) => setPageSize(Number(value))}>
            <SelectTrigger className="h-8 w-[110px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10 / 页</SelectItem>
              <SelectItem value="20">20 / 页</SelectItem>
              <SelectItem value="50">50 / 页</SelectItem>
            </SelectContent>
          </Select>
          <Pagination className="mx-0 w-auto justify-end">
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious onClick={() => setPage((prev) => Math.max(1, prev - 1))} disabled={page <= 1} />
              </PaginationItem>
              {Array.from({ length: totalPages }).slice(0, 5).map((_, idx) => {
                const pageNumber = idx + 1;
                return (
                  <PaginationItem key={pageNumber}>
                    <PaginationLink isActive={pageNumber === page} onClick={() => setPage(pageNumber)}>{pageNumber}</PaginationLink>
                  </PaginationItem>
                );
              })}
              <PaginationItem>
                <PaginationNext onClick={() => setPage((prev) => Math.min(totalPages, prev + 1))} disabled={page >= totalPages} />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      </div>

      <TransactionActionDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        seedLotOptions={seedLotOptions}
        seedLotMap={seedLotMap}
        defaultSeedLotId={seedLotDbId ?? (appliedQuery.seed_lot_id !== NONE_SELECT_VALUE ? appliedQuery.seed_lot_id : undefined)}
        onSuccess={handleSuccess}
      />
    </div>
  );
}

function optionalQueryValue(value: string | undefined) {
  if (!value || value === NONE_SELECT_VALUE) return undefined;
  return value;
}
