import { useState } from "react";
import { ListPageTemplate } from "./templates/ListPageTemplate";
import { Column } from "./organisms/DataTable";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { 
  Plus,
  Package,
  CheckCircle,
  Clock,
  AlertTriangle
} from "lucide-react";
import { ReceivingWritePage } from "./ReceivingWrite";
import { IncomingInspection } from "./IncomingInspection";

interface ReceivingRecord {
  id: string;
  lotNumber: string;
  materialNumber: string;
  item: string;
  spec: string;
  unit: string;
  quantity: number;
  weight: string;
  supplier: string;
  manufacturer: string;
  inspectionStatus: string;
  incomingInspection: string;
  judgement: string;
  managerApproval: string;
}

export function ReceivingManagement() {
  const [receivingView, setReceivingView] = useState<"list" | "write" | "inspection">("list");
  const [receivingData, setReceivingData] = useState<any>(null);

  const receivingList: ReceivingRecord[] = [
    {
      id: "1",
      lotNumber: "250723-04",
      materialNumber: "-",
      item: "EGIT-SST",
      spec: "1219*3500",
      unit: "예",
      quantity: 80,
      weight: "4,160",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionStatus: "검사대상",
      incomingInspection: "합격",
      judgement: "합격",
      managerApproval: "승인완료"
    },
    {
      id: "2",
      lotNumber: "250716-01",
      materialNumber: "-",
      item: "용강코일",
      spec: "EGIT-SST(W)350",
      unit: "롤",
      quantity: 9,
      weight: "9,210",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionStatus: "검사대상",
      incomingInspection: "대기",
      judgement: "대기",
      managerApproval: "대기"
    },
    {
      id: "3",
      lotNumber: "-",
      materialNumber: "-",
      item: "베링용장",
      spec: "3808",
      unit: "EA",
      quantity: 920,
      weight: "-",
      supplier: "대한",
      manufacturer: "대한",
      inspectionStatus: "발령",
      incomingInspection: "검사생략",
      judgement: "검사생략",
      managerApproval: "승인완료"
    }
  ];

  const getStatusBadgeVariant = (status: string): "default" | "secondary" | "destructive" | "outline" => {
    switch (status) {
      case "합격":
      case "승인완료": 
        return "default";
      case "불합격":
      case "반려": 
        return "destructive";
      case "대기": 
        return "secondary";
      default: 
        return "outline";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "합격":
      case "승인완료":
        return <CheckCircle className="w-3 h-3 mr-1" />;
      case "대기":
        return <Clock className="w-3 h-3 mr-1" />;
      case "불합격":
      case "반려":
        return <AlertTriangle className="w-3 h-3 mr-1" />;
      default:
        return null;
    }
  };

  if (receivingView === "write") {
    return (
      <ReceivingWritePage
        onBack={() => setReceivingView("list")}
        onSave={() => setReceivingView("list")}
      />
    );
  }

  if (receivingView === "inspection") {
    return (
      <IncomingInspection
        onBack={() => setReceivingView("list")}
        receivingData={receivingData}
      />
    );
  }

  const columns: Column<ReceivingRecord>[] = [
    {
      key: "lotNumber",
      label: "로트번호",
      render: (value) => <span className="font-mono">{value}</span>
    },
    {
      key: "materialNumber",
      label: "자재번호",
      render: (value) => <span className="font-mono">{value}</span>
    },
    {
      key: "item",
      label: "품목"
    },
    {
      key: "spec",
      label: "규격"
    },
    {
      key: "quantity",
      label: "수량",
      render: (value, row) => `${value} ${row.unit}`
    },
    {
      key: "weight",
      label: "중량(kg)"
    },
    {
      key: "supplier",
      label: "납품업체"
    },
    {
      key: "manufacturer",
      label: "제조사"
    },
    {
      key: "inspectionStatus",
      label: "검사상태",
      render: (value) => (
        <Badge variant="outline">
          {value}
        </Badge>
      )
    },
    {
      key: "incomingInspection",
      label: "수입검사",
      render: (value) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {getStatusIcon(value as string)}
          {value}
        </Badge>
      )
    },
    {
      key: "judgement",
      label: "판정",
      render: (value) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {getStatusIcon(value as string)}
          {value}
        </Badge>
      )
    },
    {
      key: "managerApproval",
      label: "팀장승인",
      render: (value) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {getStatusIcon(value as string)}
          {value}
        </Badge>
      )
    }
  ];

  return (
    <ListPageTemplate
      title="입고 관리"
      description="자재 입고 내역 및 관리"
      icon={Package}
      actions={
        <Button onClick={() => setReceivingView("write")}>
          <Plus className="w-4 h-4 mr-2" />
          입고 등록
        </Button>
      }
      searchPlaceholder=""
      filterButton={false}
      showSearch={false}
      data={receivingList}
      keyField="id"
      columns={columns}
      renderMobileCard={(item) => ({
        title: item.item,
        subtitle: item.spec,
        icon: (
          <div className="flex items-center gap-2">
            {item.lotNumber !== "-" && (
              <Badge variant="outline" className="font-mono text-xs">
                {item.lotNumber}
              </Badge>
            )}
            <Badge variant="outline" className="text-xs">
              {item.inspectionStatus}
            </Badge>
          </div>
        ),
        badge: {
          label: item.judgement,
          variant: getStatusBadgeVariant(item.judgement)
        },
        fields: [
          {
            label: "수량",
            value: `${item.quantity} ${item.unit}`
          },
          {
            label: "중량",
            value: `${item.weight} kg`
          },
          {
            label: "납품업체",
            value: item.supplier
          },
          {
            label: "제조사",
            value: item.manufacturer
          },
          {
            label: "수입검사",
            value: item.incomingInspection
          },
          {
            label: "팀장승인",
            value: item.managerApproval
          }
        ],
        actions: []
      })}
      emptyIcon={Package}
      emptyTitle="입고 데이터가 없습니다"
      emptyDescription="입고 내역을 등록해주세요"
    />
  );
}
