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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { 
  Package, 
  TrendingUp, 
  TrendingDown,
  AlertTriangle,
  CheckCircle,
  Download,
  RefreshCw,
  Box,
  BarChart3
} from "lucide-react";

interface StockItem {
  id: string;
  itemCode: string;
  itemName: string;
  category: string;
  spec: string;
  unit: string;
  currentStock: number;
  safetyStock: number;
  maxStock: number;
  location: string;
  lastReceiving: string;
  lastShipping: string;
  unitPrice: number;
  totalValue: number;
  status: "정상" | "부족" | "과다";
}

export function StockStatus() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");

  const stockData: StockItem[] = [
    {
      id: "1",
      itemCode: "EGIT-SST",
      itemName: "EGIT-SST 강판",
      category: "원자재",
      spec: "1219*3500",
      unit: "예",
      currentStock: 450,
      safetyStock: 200,
      maxStock: 800,
      location: "A-01",
      lastReceiving: "2025-01-15",
      lastShipping: "2025-01-18",
      unitPrice: 52000,
      totalValue: 23400000,
      status: "정상"
    },
    {
      id: "2",
      itemCode: "KSS-01",
      itemName: "용강코일",
      category: "원자재",
      spec: "EGIT-SST(W)350",
      unit: "롤",
      currentStock: 15,
      safetyStock: 20,
      maxStock: 50,
      location: "A-02",
      lastReceiving: "2025-01-10",
      lastShipping: "2025-01-17",
      unitPrice: 1023000,
      totalValue: 15345000,
      status: "부족"
    },
    {
      id: "3",
      itemCode: "BRG-3808",
      itemName: "베어링용장",
      category: "부품",
      spec: "3808",
      unit: "EA",
      currentStock: 2500,
      safetyStock: 1000,
      maxStock: 5000,
      location: "B-15",
      lastReceiving: "2025-01-12",
      lastShipping: "2025-01-19",
      unitPrice: 850,
      totalValue: 2125000,
      status: "정상"
    },
    {
      id: "4",
      itemCode: "ALU-6063",
      itemName: "알루미늄 가이드레일",
      category: "부품",
      spec: "6063-T5, 3000mm",
      unit: "M",
      currentStock: 850,
      safetyStock: 500,
      maxStock: 2000,
      location: "B-08",
      lastReceiving: "2025-01-14",
      lastShipping: "2025-01-18",
      unitPrice: 12500,
      totalValue: 10625000,
      status: "정상"
    },
    {
      id: "5",
      itemCode: "PWD-BK",
      itemName: "분체 파우더 (흑색)",
      category: "부자재",
      spec: "RAL 9005",
      unit: "kg",
      currentStock: 45,
      safetyStock: 100,
      maxStock: 300,
      location: "C-05",
      lastReceiving: "2025-01-08",
      lastShipping: "2025-01-19",
      unitPrice: 15000,
      totalValue: 675000,
      status: "부족"
    },
    {
      id: "6",
      itemCode: "SCR-NET",
      itemName: "스크린 망",
      category: "부품",
      spec: "1200*2000",
      unit: "롤",
      currentStock: 120,
      safetyStock: 80,
      maxStock: 200,
      location: "B-12",
      lastReceiving: "2025-01-16",
      lastShipping: "2025-01-20",
      unitPrice: 45000,
      totalValue: 5400000,
      status: "정상"
    },
    {
      id: "7",
      itemCode: "BOLT-M8",
      itemName: "볼트 M8x20",
      category: "부자재",
      spec: "M8x20, SUS304",
      unit: "EA",
      currentStock: 15000,
      safetyStock: 5000,
      maxStock: 30000,
      location: "C-20",
      lastReceiving: "2025-01-11",
      lastShipping: "2025-01-19",
      unitPrice: 50,
      totalValue: 750000,
      status: "과다"
    },
    {
      id: "8",
      itemCode: "CHAIN-04",
      itemName: "체인 4mm",
      category: "부품",
      spec: "4mm, 니켈도금",
      unit: "M",
      currentStock: 5800,
      safetyStock: 3000,
      maxStock: 10000,
      location: "B-18",
      lastReceiving: "2025-01-13",
      lastShipping: "2025-01-18",
      unitPrice: 1200,
      totalValue: 6960000,
      status: "정상"
    }
  ];

  const filteredData = stockData.filter(item => {
    const matchesSearch = 
      item.itemCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.itemName.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = filterCategory === "all" || item.category === filterCategory;
    const matchesStatus = filterStatus === "all" || item.status === filterStatus;
    
    return matchesSearch && matchesCategory && matchesStatus;
  });

  const totalValue = stockData.reduce((sum, item) => sum + item.totalValue, 0);
  const normalStockItems = stockData.filter(item => item.status === "정상").length;
  const lowStockItems = stockData.filter(item => item.status === "부족").length;
  const overStockItems = stockData.filter(item => item.status === "과다").length;

  const getStatusBadgeVariant = (status: string): "default" | "secondary" | "destructive" => {
    switch (status) {
      case "정상": return "default";
      case "부족": return "destructive";
      case "과다": return "secondary";
      default: return "default";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "정상": return <CheckCircle className="w-3 h-3 mr-1" />;
      case "부족": return <AlertTriangle className="w-3 h-3 mr-1" />;
      case "과다": return <TrendingUp className="w-3 h-3 mr-1" />;
      default: return null;
    }
  };

  const getStockLevel = (current: number, safety: number, max: number) => {
    const percentage = (current / max) * 100;
    if (current < safety) return { color: "bg-red-500", percentage };
    if (current > max * 0.8) return { color: "bg-orange-500", percentage };
    return { color: "bg-green-500", percentage };
  };

  const stats = [
    {
      label: "전체 품목",
      value: stockData.length,
      icon: Box,
      iconColor: "text-purple-600"
    },
    {
      label: "총 재고 가치",
      value: `${(totalValue / 100000000).toFixed(1)}억원`,
      icon: BarChart3,
      iconColor: "text-blue-600"
    },
    {
      label: "정상 재고",
      value: normalStockItems,
      icon: CheckCircle,
      iconColor: "text-green-600"
    },
    {
      label: "부족 재고",
      value: lowStockItems,
      icon: TrendingDown,
      iconColor: "text-red-600"
    }
  ];

  const columns: Column<StockItem>[] = [
    {
      key: "itemCode",
      label: "품목코드",
      width: "120px",
      render: (value) => <span className="font-mono">{value}</span>
    },
    {
      key: "itemName",
      label: "품목명"
    },
    {
      key: "category",
      label: "카테고리",
      render: (value) => (
        <Badge variant="outline">
          {value}
        </Badge>
      )
    },
    {
      key: "spec",
      label: "규격"
    },
    {
      key: "location",
      label: "위치",
      render: (value) => (
        <Badge variant="outline" className="font-mono">
          {value}
        </Badge>
      )
    },
    {
      key: "currentStock",
      label: "현재재고",
      render: (value, row) => `${(value as number).toLocaleString()} ${row.unit}`
    },
    {
      key: "safetyStock",
      label: "안전재고",
      render: (value, row) => `${(value as number).toLocaleString()} ${row.unit}`
    },
    {
      key: "stockLevel",
      label: "재고율",
      render: (value, row) => {
        const stockLevel = getStockLevel(row.currentStock, row.safetyStock, row.maxStock);
        return (
          <div className="space-y-1 min-w-[80px]">
            <div className="text-xs">
              {stockLevel.percentage.toFixed(0)}%
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
              <div 
                className={`h-full ${stockLevel.color} transition-all`}
                style={{ width: `${Math.min(stockLevel.percentage, 100)}%` }}
              />
            </div>
          </div>
        );
      }
    },
    {
      key: "totalValue",
      label: "재고가치",
      render: (value) => `₩${((value as number) / 1000000).toFixed(1)}M`
    },
    {
      key: "status",
      label: "상태",
      render: (value) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {getStatusIcon(value as string)}
          {value}
        </Badge>
      )
    }
  ];

  const extraActions = (
    <>
      <Select value={filterCategory} onValueChange={setFilterCategory}>
        <SelectTrigger className="w-[140px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">전체 카테고리</SelectItem>
          <SelectItem value="원자재">원자재</SelectItem>
          <SelectItem value="부품">부품</SelectItem>
          <SelectItem value="부자재">부자재</SelectItem>
        </SelectContent>
      </Select>
      <Select value={filterStatus} onValueChange={setFilterStatus}>
        <SelectTrigger className="w-[120px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">전체 상태</SelectItem>
          <SelectItem value="정상">정상</SelectItem>
          <SelectItem value="부족">부족</SelectItem>
          <SelectItem value="과다">과다</SelectItem>
        </SelectContent>
      </Select>
    </>
  );

  return (
    <ListPageTemplate
      title="재고 현황"
      description="실시간 재고 모니터링 및 관리"
      icon={Package}
      actions={
        <div className="flex items-center gap-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            새로고침
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            내보내기
          </Button>
        </div>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="품목코드 또는 품목명으로 검색..."
      filterButton={false}
      extraActions={extraActions}
      data={filteredData}
      keyField="id"
      columns={columns}
      renderMobileCard={(item) => {
        const stockLevel = getStockLevel(item.currentStock, item.safetyStock, item.maxStock);
        return {
          title: item.itemName,
          subtitle: item.itemCode,
          icon: (
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="font-mono text-xs">
                {item.itemCode}
              </Badge>
              <Badge variant="outline" className="text-xs">
                {item.location}
              </Badge>
            </div>
          ),
          badge: {
            label: item.status,
            variant: getStatusBadgeVariant(item.status)
          },
          fields: [
            {
              label: "현재재고",
              value: `${item.currentStock.toLocaleString()} ${item.unit}`
            },
            {
              label: "안전재고",
              value: `${item.safetyStock.toLocaleString()} ${item.unit}`
            },
            {
              label: "재고율",
              value: `${stockLevel.percentage.toFixed(0)}%`
            },
            {
              label: "카테고리",
              value: item.category
            },
            {
              label: "재고가치",
              value: `₩${(item.totalValue / 1000000).toFixed(1)}M`
            }
          ],
          actions: []
        };
      }}
      emptyIcon={Package}
      emptyTitle="재고 데이터가 없습니다"
      emptyDescription="재고 품목을 등록해주세요"
    />
  );
}
