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 { Box, Plus, Grid, Maximize2, CheckCircle } from "lucide-react";
import { ModelRegistration } from "./ModelRegistration";
import { toast } from "sonner@2.0.3";

interface Model {
  id: string;
  code: string;
  name: string;
  bodyType: string;
  status: string;
}

const initialModels: Model[] = [
  {
    id: "1",
    code: "SCR-001",
    name: "실리카 스크린 표준형",
    bodyType: "스크린",
    status: "활성"
  },
  {
    id: "2",
    code: "STL-001",
    name: "철재 방화셔터 기본형",
    bodyType: "철재",
    status: "활성"
  }
];

export function ModelManagement() {
  const [models, setModels] = useState<Model[]>(initialModels);
  const [searchTerm, setSearchTerm] = useState("");
  const [view, setView] = useState<"list" | "create">("list");
  const [editingModel, setEditingModel] = useState<Model | null>(null);

  const filteredModels = models.filter(model => 
    model.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
    model.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    model.bodyType.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleSave = (data: any) => {
    if (editingModel) {
      // 수정
      setModels(models.map(m => 
        m.id === editingModel.id 
          ? { ...m, ...data }
          : m
      ));
      toast.success("모델이 수정되었습니다.");
    } else {
      // 신규 등록
      const newModel: Model = {
        id: Date.now().toString(),
        code: data.code || "",
        name: data.name || "",
        bodyType: data.bodyType || "",
        status: "활성"
      };
      setModels([...models, newModel]);
      toast.success(`모델 "${data.name}" (${data.code})이 성공적으로 등록되었습니다.`);
    }
    setView("list");
    setEditingModel(null);
  };

  const handleDelete = (id: string) => {
    if (confirm("모델을 삭제하시겠습니까?")) {
      setModels(models.filter(m => m.id !== id));
      toast.success("모델이 삭제되었습니다.");
    }
  };

  const openCreatePage = () => {
    setEditingModel(null);
    setView("create");
  };

  const openEditPage = (model: Model) => {
    setEditingModel(model);
    setView("create");
  };

  const columns: Column<Model>[] = [
    {
      key: "code",
      label: "모델코드"
    },
    {
      key: "name",
      label: "모델명"
    },
    {
      key: "bodyType",
      label: "본체타입",
      render: (value) => (
        <Badge variant="outline">
          {value}
        </Badge>
      )
    },
    {
      key: "status",
      label: "상태",
      render: (value) => (
        <Badge variant={value === "활성" ? "default" : "secondary"}>
          {value}
        </Badge>
      )
    }
  ];

  if (view === "create") {
    return (
      <ModelRegistration
        onCancel={() => setView("list")}
        onSave={handleSave}
      />
    );
  }

  return (
    <ListPageTemplate
      title="모델 목록"
      description="제품 모델 템플릿 관리"
      icon={Box}
      stats={[
        {
          label: "전체 모델",
          value: models.length,
          icon: Box,
          iconColor: "text-blue-600"
        },
        {
          label: "스크린 모델",
          value: models.filter(m => m.bodyType === "스크린").length,
          icon: Grid,
          iconColor: "text-purple-600"
        },
        {
          label: "철재 모델",
          value: models.filter(m => m.bodyType === "철재").length,
          icon: Maximize2,
          iconColor: "text-green-600"
        },
        {
          label: "활성 모델",
          value: models.filter(m => m.status === "활성").length,
          icon: CheckCircle,
          iconColor: "text-orange-600"
        }
      ]}
      actions={
        <Button onClick={openCreatePage}>
          <Plus className="w-4 h-4 mr-2" />
          모델 등록
        </Button>
      }
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="코드/모델명 검색..."
      data={filteredModels}
      keyField="id"
      columns={columns}
      renderMobileCard={(model) => ({
        title: model.name,
        subtitle: model.code,
        badge: {
          label: model.status,
          variant: model.status === "활성" ? "default" : "secondary"
        },
        fields: [
          {
            label: "본체타입",
            value: model.bodyType
          }
        ],
        actions: [
          {
            label: "수정",
            onClick: () => openEditPage(model)
          },
          {
            label: "삭제",
            onClick: () => handleDelete(model.id),
            variant: "destructive"
          }
        ]
      })}
      emptyIcon={Box}
      emptyTitle="모델이 없습니다"
      emptyDescription="새 모델을 등록해주세요"
    />
  );
}
