/**
 * 단가관리 목록 페이지
 * 
 * ResponsiveListTemplate 적용
 * - 데스크톱: TabsList + DataTable
 * - 모바일: 커스텀 버튼 탭 + 카드 리스트
 * - 완전한 반응형 지원
 */

import { useState, useMemo } from "react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { 
  DollarSign, 
  Plus, 
  Edit,
  Package,
  TrendingUp,
  CheckCircle2,
  AlertCircle,
  History
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData, ItemMaster } from "./contexts/DataContext";
import { PricingData } from "./PricingWrite";
import { 
  ResponsiveListTemplate, 
  TabConfig, 
  createMobileCardRenderer 
} from "./templates/ResponsiveListTemplate";
import { Column } from "./organisms/DataTable";
import { TableAction } from "./molecules/TableActions";

interface PricingManagementListProps {
  onNewPricing: (item: ItemMaster) => void;
  onEditPricing: (pricing: PricingData) => void;
  onSyncFromItemMaster: () => void;
  pricings: PricingData[];
}

export function PricingManagementList({ 
  onNewPricing, 
  onEditPricing, 
  onSyncFromItemMaster, 
  pricings 
}: PricingManagementListProps) {
  const { itemMasters } = useData();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedItemType, setSelectedItemType] = useState<string>("all");

  // 필터링된 품목 목록
  const filteredItems = useMemo(() => {
    return itemMasters.filter(item => {
      const matchesSearch = 
        item.itemCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.itemName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.specification?.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesType = selectedItemType === "all" || item.itemType === selectedItemType;
      
      return matchesSearch && matchesType;
    });
  }, [itemMasters, pricings, searchTerm, selectedItemType]);

  // 통계 계산
  const stats = useMemo(() => {
    const totalItems = itemMasters.length;
    const registeredCount = pricings.length;
    const notRegisteredCount = totalItems - registeredCount;
    const finalizedCount = pricings.filter(p => p.isFinal).length;

    return [
      {
        label: "전체 품목",
        value: totalItems,
        icon: Package,
        iconColor: "text-blue-600"
      },
      {
        label: "단가 등록",
        value: registeredCount,
        icon: DollarSign,
        iconColor: "text-green-600"
      },
      {
        label: "미등록",
        value: notRegisteredCount,
        icon: AlertCircle,
        iconColor: "text-orange-600"
      },
      {
        label: "확정",
        value: finalizedCount,
        icon: CheckCircle2,
        iconColor: "text-purple-600"
      }
    ];
  }, [itemMasters, pricings]);

  // 품목 타입별 개수
  const getTypeCount = (type: string) => {
    if (type === "all") return itemMasters.length;
    return itemMasters.filter(item => item.itemType === type).length;
  };

  // 탭 구성
  const tabs: TabConfig[] = [
    {
      value: "all",
      label: "전체",
      count: getTypeCount("all"),
      color: "blue",
    },
    {
      value: "FG",
      label: "제품",
      count: getTypeCount("FG"),
      color: "purple",
    },
    {
      value: "PT",
      label: "부품",
      count: getTypeCount("PT"),
      color: "orange",
    },
    {
      value: "SM",
      label: "부자재",
      count: getTypeCount("SM"),
      color: "cyan",
    },
    {
      value: "RM",
      label: "원자재",
      count: getTypeCount("RM"),
      color: "green",
    },
    {
      value: "CS",
      label: "소모품",
      count: getTypeCount("CS"),
      color: "gray",
    },
    {
      value: "BENDING",
      label: "절곡물",
      count: getTypeCount("BENDING"),
      color: "indigo",
    },
  ];

  // 품목 타입 라벨
  const getItemTypeLabel = (type: string) => {
    switch (type) {
      case 'RM': return '원자재';
      case 'PT': return '부품';
      case 'FG': return '제품';
      case 'SM': return '부자재';
      case 'CS': return '소모품';
      case 'BENDING': return '절곡물';
      default: return type;
    }
  };

  // 품목 타입 뱃지
  const getItemTypeBadge = (type: string) => {
    switch (type) {
      case 'RM':
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">원자재</Badge>;
      case 'PT':
        return <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200">부품</Badge>;
      case 'FG':
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">제품</Badge>;
      case 'SM':
        return <Badge variant="outline" className="bg-cyan-50 text-cyan-700 border-cyan-200">부자재</Badge>;
      case 'CS':
        return <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">소모품</Badge>;
      case 'BENDING':
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">절곡물</Badge>;
      default:
        return <Badge variant="outline">{type}</Badge>;
    }
  };

  // 상태 뱃지
  const getStatusBadge = (pricing: PricingData | undefined) => {
    if (!pricing) {
      return <Badge variant="outline" className="bg-gray-50 text-gray-700">미등록</Badge>;
    }
    if (pricing.isFinal) {
      return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">확정</Badge>;
    }
    if (pricing.status === 'active') {
      return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">활성</Badge>;
    }
    if (pricing.status === 'inactive') {
      return <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">비활성</Badge>;
    }
    return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">초안</Badge>;
  };

  // 단가 정보 가져오기
  const getPricingInfo = (item: ItemMaster) => {
    return pricings.find(p => p.itemId === item.id || p.itemCode === item.itemCode);
  };

  // 마진율 계산
  const calculateDisplayMargin = (pricing: PricingData) => {
    if (pricing.marginRate !== undefined) {
      return pricing.marginRate;
    }
    
    const basePrice = (pricing.purchasePrice || 0) + (pricing.processingCost || 0);
    if (basePrice > 0 && pricing.salesPrice) {
      return Math.round(((pricing.salesPrice - basePrice) / basePrice) * 100);
    }
    
    return 0;
  };

  // 마진율 뱃지
  const getMarginBadge = (marginRate: number) => {
    if (marginRate === 0) {
      return <span className="text-muted-foreground">-</span>;
    }
    
    return (
      <Badge variant="outline" className={
        marginRate >= 30 ? "bg-green-50 text-green-700 border-green-200" :
        marginRate >= 20 ? "bg-blue-50 text-blue-700 border-blue-200" :
        marginRate >= 10 ? "bg-orange-50 text-orange-700 border-orange-200" :
        "bg-red-50 text-red-700 border-red-200"
      }>
        {marginRate.toFixed(1)}%
      </Badge>
    );
  };

  // 금액 포맷팅
  const formatPrice = (price: number | undefined) => {
    if (!price) return "-";
    return `${price.toLocaleString()}원`;
  };

  // DataTable용 컬럼 정의
  const tableColumns: Column<ItemMaster>[] = [
    {
      key: "rowNumber",
      label: "번호",
      type: "text",
      width: "60px",
      render: (_, __, index) => String((index ?? 0) + 1),
    },
    {
      key: "itemType",
      label: "품목 유형",
      type: "custom",
      width: "100px",
      render: (value) => getItemTypeBadge(value as string),
    },
    {
      key: "itemCode",
      label: "품목 코드",
      type: "text",
      width: "120px",
      render: (value) => <span className="font-mono text-sm">{value}</span>,
    },
    {
      key: "itemName",
      label: "품목명",
      type: "text",
      minWidth: "150px",
      render: (value) => <span className="font-medium">{value}</span>,
    },
    {
      key: "specification",
      label: "규격",
      type: "text",
      width: "120px",
      render: (value) => (
        <span className="text-sm text-muted-foreground">{value || "-"}</span>
      ),
    },
    {
      key: "unit",
      label: "단위",
      type: "text",
      width: "80px",
      align: "center",
    },
    {
      key: "purchasePrice",
      label: "매입단가",
      type: "text",
      width: "120px",
      align: "right",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        return (
          <span className="font-mono">
            {pricingInfo?.purchasePrice ? 
              formatPrice(pricingInfo.purchasePrice) : 
              <span className="text-muted-foreground">-</span>
            }
          </span>
        );
      },
    },
    {
      key: "processingCost",
      label: "가공비",
      type: "text",
      width: "100px",
      align: "right",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        return (
          <span className="font-mono">
            {pricingInfo?.processingCost ? 
              formatPrice(pricingInfo.processingCost) : 
              <span className="text-muted-foreground">-</span>
            }
          </span>
        );
      },
    },
    {
      key: "salesPrice",
      label: "판매단가",
      type: "text",
      width: "120px",
      align: "right",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        return (
          <span className="font-mono font-semibold">
            {pricingInfo?.salesPrice ? 
              formatPrice(pricingInfo.salesPrice) : 
              <span className="text-muted-foreground">-</span>
            }
          </span>
        );
      },
    },
    {
      key: "marginRate",
      label: "마진율",
      type: "custom",
      width: "80px",
      align: "right",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        const marginRate = pricingInfo ? calculateDisplayMargin(pricingInfo) : 0;
        return getMarginBadge(marginRate);
      },
    },
    {
      key: "effectiveDate",
      label: "적용일",
      type: "text",
      width: "100px",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        if (!pricingInfo?.effectiveDate) {
          return <span className="text-muted-foreground">-</span>;
        }
        return (
          <span className="text-sm">
            {new Date(pricingInfo.effectiveDate).toLocaleDateString('ko-KR')}
          </span>
        );
      },
    },
    {
      key: "status",
      label: "상태",
      type: "custom",
      width: "100px",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        return getStatusBadge(pricingInfo);
      },
    },
    {
      key: "actions",
      label: "작업",
      type: "actions",
      width: "120px",
      render: (_, row) => {
        const pricingInfo = getPricingInfo(row);
        const actions: TableAction[] = [];

        if (pricingInfo) {
          actions.push({
            label: "수정",
            icon: Edit,
            onClick: () => onEditPricing(pricingInfo),
            variant: "ghost" as const,
          });

          if (pricingInfo.currentRevision > 0) {
            actions.push({
              label: "이력",
              icon: History,
              onClick: () => toast.info(`${row.itemName} 단가 이력 (${pricingInfo.currentRevision}차)`),
              variant: "ghost" as const,
            });
          }
        } else {
          actions.push({
            label: "등록",
            icon: Plus,
            onClick: () => onNewPricing(row),
            variant: "ghost" as const,
          });
        }

        return actions;
      },
    },
  ];

  // 모바일 카드 렌더러
  const renderMobileCard = createMobileCardRenderer<ItemMaster>({
    getTitle: (item) => item.itemName,
    getSubtitle: (item) => item.itemCode,
    getBadge: (item) => {
      const pricingInfo = getPricingInfo(item);
      if (!pricingInfo) {
        return { label: "미등록", variant: "outline" };
      }
      if (pricingInfo.isFinal) {
        return { label: "확정", variant: "default" };
      }
      if (pricingInfo.status === 'active') {
        return { label: "활성", variant: "default" };
      }
      return { label: "초안", variant: "secondary" };
    },
    getFields: (item) => {
      const pricingInfo = getPricingInfo(item);
      const marginRate = pricingInfo ? calculateDisplayMargin(pricingInfo) : 0;
      
      return [
        { label: "품목 유형", value: getItemTypeLabel(item.itemType) },
        { label: "규격", value: item.specification || "-" },
        { label: "단위", value: item.unit },
        { label: "매입단가", value: formatPrice(pricingInfo?.purchasePrice) },
        { label: "가공비", value: formatPrice(pricingInfo?.processingCost) },
        { label: "판매단가", value: formatPrice(pricingInfo?.salesPrice) },
        { label: "마진율", value: marginRate > 0 ? `${marginRate.toFixed(1)}%` : "-" },
        { 
          label: "적용일", 
          value: pricingInfo?.effectiveDate 
            ? new Date(pricingInfo.effectiveDate).toLocaleDateString('ko-KR')
            : "-"
        },
      ];
    },
    getActions: (item) => {
      const pricingInfo = getPricingInfo(item);
      
      return (
        <div className="flex gap-2 flex-wrap">
          {pricingInfo ? (
            <>
              <Button size="sm" variant="outline" onClick={() => onEditPricing(pricingInfo)}>
                <Edit className="w-4 h-4 mr-1" />
                수정
              </Button>
              {pricingInfo.currentRevision > 0 && (
                <Button 
                  size="sm" 
                  variant="outline" 
                  onClick={() => toast.info(`${item.itemName} 단가 이력 (${pricingInfo.currentRevision}차)`)}
                >
                  <History className="w-4 h-4 mr-1" />
                  이력
                </Button>
              )}
            </>
          ) : (
            <Button 
              size="sm" 
              variant="outline" 
              onClick={() => onNewPricing(item)}
              className="bg-blue-50 border-blue-200 text-blue-700 hover:bg-blue-100"
            >
              <Plus className="w-4 h-4 mr-1" />
              등록
            </Button>
          )}
        </div>
      );
    },
  });

  return (
    <ResponsiveListTemplate
      title="단가 목록"
      description="품목별 매입단가, 판매단가 및 마진을 관리합니다"
      icon={DollarSign}
      headerActions={
        <Button 
          variant="outline" 
          onClick={onSyncFromItemMaster}
          className="gap-2"
        >
          <TrendingUp className="h-4 w-4" />
          품목 마스터 동기화
        </Button>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="품목 코드, 품목명, 규격 검색..."
      tabs={tabs}
      currentTab={selectedItemType}
      onTabChange={setSelectedItemType}
      data={filteredItems}
      keyField="id"
      columns={tableColumns}
      renderMobileCard={renderMobileCard}
      cardTitle={(currentTab, count) => {
        const tabConfig = tabs.find((t) => t.value === currentTab);
        return `${tabConfig?.label || "목록"} (${count}개)`;
      }}
      emptyMessage="조건에 맞는 품목이 없습니다"
      maxWidth="full"
    />
  );
}