"use client";

/**
 * 재고생산관리 - 목록 페이지
 *
 * 수주관리(order-management-sales)를 기반으로 단순화
 * - 거래처/배송/할인/개소 제거
 * - order_type=STOCK 필터
 * - UniversalListPage 패턴 사용
 */

import { useState, useEffect, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import {
  Factory,
  Trash2,
  Edit,
  Eye,
  Loader2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
  type FilterFieldConfig,
} from "@/components/templates/UniversalListPage";
import { toast } from "sonner";
import { TableRow, TableCell } from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { ListMobileCard, InfoField } from "@/components/organisms/MobileCard";
import { DeleteConfirmDialog } from "@/components/ui/confirm-dialog";
import {
  getStockOrders,
  deleteStockOrder,
  deleteStockOrders,
  type StockOrder,
  type StockStatus,
} from "./actions";

// 상태 뱃지
function getStatusBadge(status: StockStatus) {
  const config: Record<StockStatus, { label: string; className: string }> = {
    draft: { label: "등록", className: "bg-gray-100 text-gray-700 border-gray-200" },
    confirmed: { label: "확정", className: "bg-blue-100 text-blue-700 border-blue-200" },
    in_progress: { label: "생산지시완료", className: "bg-indigo-100 text-indigo-700 border-indigo-200" },
    in_production: { label: "생산중", className: "bg-green-100 text-green-700 border-green-200" },
    produced: { label: "생산완료", className: "bg-teal-100 text-teal-700 border-teal-200" },
    completed: { label: "생산완료", className: "bg-teal-100 text-teal-700 border-teal-200" },
    cancelled: { label: "취소", className: "bg-red-100 text-red-700 border-red-200" },
  };
  const c = config[status] || config.draft;
  return <BadgeSm className={c.className}>{c.label}</BadgeSm>;
}

export function StockProductionList() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 필터
  const [startDate, setStartDate] = useState<string>("");
  const [endDate, setEndDate] = useState<string>("");

  // 필터
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    status: 'all',
  });

  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'status',
      label: '상태',
      type: 'single',
      options: [
        { value: 'draft', label: '등록' },
        { value: 'confirmed', label: '확정' },
        { value: 'in_progress', label: '생산지시완료' },
        { value: 'in_production', label: '생산중' },
        { value: 'completed', label: '생산완료' },
      ],
      allOptionLabel: '전체',
    },
  ];

  // 삭제 다이얼로그
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetIds, setDeleteTargetIds] = useState<string[]>([]);
  const [isDeleting, setIsDeleting] = useState(false);

  // API 데이터
  const [orders, setOrders] = useState<StockOrder[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 데이터 로드
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const ordersResult = await getStockOrders();

      if (ordersResult.success && ordersResult.data) {
        setOrders(ordersResult.data.items);
      } else {
        toast.error(ordersResult.error || "재고생산 목록을 불러오는데 실패했습니다.");
      }
    } catch (error) {
      console.error("Error loading stock orders:", error);
      toast.error("데이터를 불러오는 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 필터링 및 정렬
  const filteredOrders = orders
    .filter((order) => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        !searchTerm ||
        order.orderNo.toLowerCase().includes(searchLower) ||
        order.itemSummary.toLowerCase().includes(searchLower) ||
        (order.items?.[0]?.itemCode || '').toLowerCase().includes(searchLower) ||
        (order.bendingLot?.lotNumber || '').toLowerCase().includes(searchLower);

      const statusFilter = filterValues.status as string;
      const matchesFilter = !statusFilter || statusFilter === "all" || order.status === statusFilter;

      return matchesSearch && matchesFilter;
    })
    .sort((a, b) => new Date(b.regDate).getTime() - new Date(a.regDate).getTime());

  // 핸들러
  const handleView = (order: StockOrder) => {
    router.push(`/sales/stocks/${order.id}?mode=view`);
  };

  const handleEdit = (order: StockOrder) => {
    router.push(`/sales/stocks/${order.id}?mode=edit`);
  };

  const handleDelete = (orderId: string) => {
    setDeleteTargetIds([orderId]);
    setIsDeleteDialogOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (deleteTargetIds.length === 0) return;
    setIsDeleting(true);
    try {
      if (deleteTargetIds.length === 1) {
        const result = await deleteStockOrder(deleteTargetIds[0]);
        if (result.success) {
          setOrders(orders.filter((o) => o.id !== deleteTargetIds[0]));
          setSelectedItems(new Set());
          toast.success("재고생산이 삭제되었습니다.");
        } else {
          toast.error(result.error || "삭제에 실패했습니다.");
        }
      } else {
        const result = await deleteStockOrders(deleteTargetIds);
        if (result.success) {
          const skippedSet = new Set((result.skippedIds ?? []).map(String));
          setOrders(orders.filter((o) => skippedSet.has(o.id) || !deleteTargetIds.includes(o.id)));
          setSelectedItems(new Set());
          if (result.deletedCount) toast.success(`${result.deletedCount}개 삭제되었습니다.`);
          if (result.skippedCount) toast.warning(`${result.skippedCount}개는 삭제할 수 없습니다.`);
        } else {
          toast.error(result.error || "삭제에 실패했습니다.");
        }
      }
    } catch (error) {
      console.error("Error deleting:", error);
      toast.error("삭제 중 오류가 발생했습니다.");
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
      setDeleteTargetIds([]);
    }
  };

  // 체크박스 선택
  const paginatedOrders = filteredOrders.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const toggleSelection = (id: string) => {
    const next = new Set(selectedItems);
    next.has(id) ? next.delete(id) : next.add(id);
    setSelectedItems(next);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === paginatedOrders.length && paginatedOrders.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedOrders.map((o) => o.id)));
    }
  };

  // 테이블 컬럼
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: "rowNumber", label: "번호", className: "px-2 text-center w-[60px]" },
    { key: "orderNo", label: "생산번호", className: "px-2", sortable: true, copyable: true },
    { key: "itemCode", label: "품목코드", className: "px-2", sortable: true, copyable: true },
    { key: "lotNumber", label: "로트번호", className: "px-2", copyable: true },
    { key: "itemSummary", label: "품목명", className: "px-2", sortable: true, copyable: true },
    { key: "quantity", label: "수량", className: "px-2 text-center", sortable: true },
    { key: "regDate", label: "등록일", className: "px-2", sortable: true, copyable: true },
    { key: "status", label: "상태", className: "px-2 text-center", sortable: true },
    { key: "memo", label: "비고", className: "px-2", copyable: true },
  ], []);

  // 테이블 행 렌더링
  const renderTableRow = (
    order: StockOrder,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <TableRow
        key={order.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? "bg-blue-50" : ""}`}
        onClick={() => handleView(order)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox checked={isSelected} onCheckedChange={onToggle} />
        </TableCell>
        <TableCell className="text-center">{globalIndex}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
            {order.orderNo}
          </code>
        </TableCell>
        <TableCell>
          {order.items?.[0]?.itemCode ? (
            <code className="text-xs bg-purple-50 text-purple-700 px-2 py-1 rounded font-mono">
              {order.items[0].itemCode}
            </code>
          ) : "-"}
        </TableCell>
        <TableCell>
          {order.bendingLot?.lotNumber ? (
            <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
              {order.bendingLot.lotNumber}
            </code>
          ) : "-"}
        </TableCell>
        <TableCell>{order.itemSummary || "-"}</TableCell>
        <TableCell className="text-center">{order.quantity || "-"}</TableCell>
        <TableCell>{order.regDate || "-"}</TableCell>
        <TableCell className="text-center">{getStatusBadge(order.status)}</TableCell>
        <TableCell className="max-w-[150px] truncate">{order.memo || "-"}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드
  const renderMobileCard = (
    order: StockOrder,
    _index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <ListMobileCard
        key={order.id}
        id={order.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleView(order)}
        headerBadges={
          <>
            <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
              {globalIndex}
            </Badge>
            <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
              {order.orderNo}
            </code>
          </>
        }
        title={order.itemSummary}
        statusBadge={getStatusBadge(order.status)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="수량" value={`${order.quantity}`} />
            <InfoField label="등록일" value={order.regDate || "-"} />
            <InfoField label="로트번호" value={order.bendingLot?.lotNumber || "-"} />
            <InfoField label="품목 수" value={`${order.itemCount}개`} />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleView(order); }}
              >
                <Eye className="h-4 w-4 mr-2" />
                상세
              </Button>
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleEdit(order); }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              {(order.status === "draft" || order.status === "confirmed") && (
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600"
                  onClick={(e) => { e.stopPropagation(); handleDelete(order.id); }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
              )}
            </div>
          ) : undefined
        }
      />
    );
  };

  // UniversalListPage config
  const listConfig: UniversalListConfig<StockOrder> = {
    title: "재고생산 목록",
    description: "재고생산 관리 및 생산지시 연동",
    icon: Factory,
    basePath: "/sales/stocks",
    idField: "id",

    actions: {
      getList: async () => ({
        success: true,
        data: filteredOrders,
        totalCount: filteredOrders.length,
      }),
      deleteItem: async (id) => {
        const result = await deleteStockOrder(id);
        if (result.success) {
          setOrders((prev) => prev.filter((o) => o.id !== id));
        }
        return result;
      },
      deleteBulk: async (ids) => {
        const result = await deleteStockOrders(ids);
        if (result.success) {
          const skippedSet = new Set((result.skippedIds ?? []).map(String));
          setOrders((prev) => prev.filter((o) => skippedSet.has(o.id) || !ids.includes(o.id)));
        }
        return result;
      },
    },

    columns: tableColumns,

    searchPlaceholder: "생산번호, 품목명, 로트번호 검색...",

    dateRangeSelector: {
      enabled: true,
      showPresets: true,
      presetsPosition: 'inline',
      startDate,
      endDate,
      onStartDateChange: setStartDate,
      onEndDateChange: setEndDate,
      dateField: "regDate",
    },

    itemsPerPage,
    clientSideFiltering: true,

    searchFilter: (order, searchValue) => {
      const s = searchValue.toLowerCase();
      return (
        order.orderNo.toLowerCase().includes(s) ||
        order.itemSummary.toLowerCase().includes(s) ||
        (order.bendingLot?.lotNumber || '').toLowerCase().includes(s)
      );
    },

    customFilterFn: (items, fv) => {
      if (!items || items.length === 0) return items;
      return items.filter((item) => {
        const statusVal = fv.status as string;
        if (statusVal && statusVal !== 'all' && item.status !== statusVal) return false;
        return true;
      });
    },

    headerActions: () => (
      <div className="flex items-center gap-2 ml-auto">
        <Button onClick={() => router.push("/sales/stocks?mode=new")}>
          <Factory className="w-4 h-4 mr-2" />
          재고생산 등록
        </Button>
      </div>
    ),

    filterConfig,
    initialFilters: filterValues,
    filterTitle: '재고생산 필터',

    renderTableRow,
    renderMobileCard,

    renderDialogs: () => (
      <DeleteConfirmDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleConfirmDelete}
        title="삭제 확인"
        description={
          <>
            선택한 <strong>{deleteTargetIds.length}개</strong>의 재고생산을 삭제하시겠습니까?
            <br />
            <span className="text-muted-foreground text-sm">
              삭제된 재고생산은 복구할 수 없습니다.
            </span>
          </>
        }
        loading={isDeleting}
      />
    ),
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">재고생산 목록을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <UniversalListPage<StockOrder>
      config={listConfig}
      initialData={filteredOrders}
      initialTotalCount={filteredOrders.length}
      externalSelection={{
        selectedItems,
        onToggleSelection: toggleSelection,
        onToggleSelectAll: toggleSelectAll,
        setSelectedItems,
        getItemId: (item: StockOrder) => item.id,
      }}
      onFilterChange={(newFilters) => {
        setFilterValues(newFilters);
        setCurrentPage(1);
      }}
      onSearchChange={setSearchTerm}
    />
  );
}
