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 { Plus, Package, Box, Component, Factory } from "lucide-react";
import { toast } from "sonner@2.0.3";
import { ProductsRegistration } from "./ProductsRegistration";

interface Product {
  id: string;
  code: string;
  name: string;
  category: string;
  spec: string;
  unit: string;
}

const initialProducts: Product[] = [
  {
    id: "1",
    code: "EGI-1.15",
    name: "철국판",
    category: "원자재",
    spec: "EGI-1.55T-1219*3000",
    unit: "㎡"
  },
  {
    id: "2",
    code: "SUS-1.2",
    name: "철국코일",
    category: "원자재",
    spec: "EGI-1.55T-W161",
    unit: "㎡"
  },
  {
    id: "3",
    code: "SHAFT-4IN",
    name: "감기샤프트",
    category: "부자재",
    spec: "4인치-114.3*2T-L6000",
    unit: "ea"
  },
  {
    id: "4",
    code: "SILICA0.84",
    name: "실리카 코팅작물",
    category: "원자재",
    spec: "0.84T-W1220",
    unit: "m"
  },
  {
    id: "5",
    code: "BODY-SILICA",
    name: "실리카스크린",
    category: "본체",
    spec: "조립형",
    unit: "ea"
  }
];

const categories = ["전체", "원자재", "부자재", "반제품", "완제품", "본체", "모터"];

export function ProductsManagement() {
  const [products, setProducts] = useState<Product[]>(initialProducts);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("전체");
  const [view, setView] = useState<"list" | "register">("list");
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // 필터링된 데이터
  const filteredProducts = products.filter(product => {
    const matchesSearch = 
      product.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      product.spec.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = categoryFilter === "전체" || product.category === categoryFilter;
    return matchesSearch && matchesCategory;
  });

  // 등록 화면으로 이동
  const openRegisterPage = (product?: Product) => {
    setEditingProduct(product || null);
    setView("register");
  };

  // 저장
  const handleSave = (productData: Omit<Product, "id">) => {
    if (editingProduct) {
      // 수정
      setProducts(products.map(p => 
        p.id === editingProduct.id 
          ? { ...p, ...productData }
          : p
      ));
      toast.success("품목이 수정되었습니다.");
    } else {
      // 신규 등록
      const newProduct: Product = {
        id: Date.now().toString(),
        ...productData
      };
      setProducts([...products, newProduct]);
      toast.success("품목이 등록되었습니다.");
    }
    setView("list");
  };

  // 삭제
  const handleDelete = (id: string) => {
    if (confirm("품목을 삭제하시겠습니까?")) {
      setProducts(products.filter(p => p.id !== id));
      toast.success("품목이 삭제되었습니다.");
    }
  };

  // 복제
  const handleDuplicate = (product: Product) => {
    const newProduct: Product = {
      id: Date.now().toString(),
      code: product.code + "-COPY",
      name: product.name + " (복사)",
      category: product.category,
      spec: product.spec,
      unit: product.unit
    };
    setProducts([...products, newProduct]);
    toast.success("품목이 복제되었습니다.");
  };

  const columns: Column<Product>[] = [
    {
      key: "code",
      label: "품목코드"
    },
    {
      key: "name",
      label: "품목명"
    },
    {
      key: "category",
      label: "분류",
      render: (value) => (
        <Badge variant="outline">
          {value}
        </Badge>
      )
    },
    {
      key: "spec",
      label: "규격"
    },
    {
      key: "unit",
      label: "단위"
    }
  ];

  // 등록 화면
  if (view === "register") {
    return (
      <ProductsRegistration
        onBack={() => setView("list")}
        onSave={handleSave}
        editingProduct={editingProduct}
      />
    );
  }

  // 목록 화면
  return (
    <ListPageTemplate
      title="품목 관리"
      description="품목코드, 품목명, 분류, 규격, 단위 정보를 관리합니다"
      icon={Package}
      stats={[
        {
          label: "전체 품목",
          value: products.length,
          icon: Package,
          iconColor: "text-blue-600"
        },
        {
          label: "원자재",
          value: products.filter(p => p.category === "원자재").length,
          icon: Box,
          iconColor: "text-purple-600"
        },
        {
          label: "부자재",
          value: products.filter(p => p.category === "부자재").length,
          icon: Component,
          iconColor: "text-green-600"
        },
        {
          label: "본체/완제품",
          value: products.filter(p => p.category === "본체" || p.category === "완제품").length,
          icon: Factory,
          iconColor: "text-orange-600"
        }
      ]}
      actions={
        <Button onClick={() => openRegisterPage()}>
          <Plus className="w-4 h-4 mr-2" />
          신규 등록
        </Button>
      }
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="코드/명/규격 검색..."
      extraActions={
        <Select value={categoryFilter} onValueChange={setCategoryFilter}>
          <SelectTrigger className="w-[150px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {categories.map(cat => (
              <SelectItem key={cat} value={cat}>{cat}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      }
      data={filteredProducts}
      keyField="id"
      columns={columns}
      renderMobileCard={(product) => ({
        title: product.name,
        subtitle: product.code,
        badge: {
          label: product.category,
          variant: "outline"
        },
        fields: [
          {
            label: "규격",
            value: product.spec
          },
          {
            label: "단위",
            value: product.unit
          }
        ],
        actions: [
          {
            label: "수정",
            onClick: () => openRegisterPage(product)
          },
          {
            label: "복제",
            onClick: () => handleDuplicate(product)
          },
          {
            label: "삭제",
            onClick: () => handleDelete(product.id),
            variant: "destructive"
          }
        ]
      })}
      emptyIcon={Package}
      emptyTitle="품목이 없습니다"
      emptyDescription="신규 품목을 등록해주세요"
    />
  );
}
