import { useState } from 'react';
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from './organisms/DataTable';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
  Calculator,
  Package,
  TrendingUp,
  DollarSign,
  Eye,
} from 'lucide-react';

interface CostData {
  id: string;
  productCode: string;
  productName: string;
  productType: string;
  materialCost: number;
  laborCost: number;
  overheadCost: number;
  totalCost: number;
  standardPrice: number;
  margin: number;
  marginRate: number;
  bomVersion: string;
  lastUpdated: string;
}

export function CostManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('전체');

  // 원가 데이터 (BOM, 생산 데이터와 연동)
  const costData: CostData[] = [
    {
      id: 'COST-001',
      productCode: 'SCR-100',
      productName: '스크린 기본형',
      productType: '완제품',
      materialCost: 85000,
      laborCost: 35000,
      overheadCost: 15000,
      totalCost: 135000,
      standardPrice: 150000,
      margin: 15000,
      marginRate: 10,
      bomVersion: 'v1.2',
      lastUpdated: '2025-03-20'
    },
    {
      id: 'COST-002',
      productCode: 'SLT-200',
      productName: '슬랫 표준형',
      productType: '완제품',
      materialCost: 125000,
      laborCost: 45000,
      overheadCost: 20000,
      totalCost: 190000,
      standardPrice: 200000,
      margin: 10000,
      marginRate: 5,
      bomVersion: 'v2.0',
      lastUpdated: '2025-03-18'
    },
    {
      id: 'COST-003',
      productCode: 'BND-300',
      productName: '절곡 제품',
      productType: '완제품',
      materialCost: 98000,
      laborCost: 52000,
      overheadCost: 18000,
      totalCost: 168000,
      standardPrice: 180000,
      margin: 12000,
      marginRate: 6.7,
      bomVersion: 'v1.1',
      lastUpdated: '2025-03-15'
    },
    {
      id: 'COST-004',
      productCode: 'MAT-006',
      productName: '헤드박스',
      productType: '부품',
      materialCost: 28000,
      laborCost: 12000,
      overheadCost: 5000,
      totalCost: 45000,
      standardPrice: 55000,
      margin: 10000,
      marginRate: 18.2,
      bomVersion: 'v1.0',
      lastUpdated: '2025-03-10'
    },
    {
      id: 'COST-005',
      productCode: 'SCR-200',
      productName: '스크린 프리미엄',
      productType: '완제품',
      materialCost: 135000,
      laborCost: 55000,
      overheadCost: 25000,
      totalCost: 215000,
      standardPrice: 220000,
      margin: 5000,
      marginRate: 2.3,
      bomVersion: 'v1.0',
      lastUpdated: '2025-03-22'
    },
  ];

  const productTypes = ['전체', '완제품', '부품'];

  const filteredCosts = costData.filter(cost => {
    const matchesSearch = cost.productCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         cost.productName.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = selectedType === '전체' || cost.productType === selectedType;
    return matchesSearch && matchesType;
  });

  const avgMaterialCost = filteredCosts.length > 0 
    ? filteredCosts.reduce((sum, item) => sum + item.materialCost, 0) / filteredCosts.length 
    : 0;
  const avgLaborCost = filteredCosts.length > 0
    ? filteredCosts.reduce((sum, item) => sum + item.laborCost, 0) / filteredCosts.length
    : 0;
  const avgTotalCost = filteredCosts.length > 0
    ? filteredCosts.reduce((sum, item) => sum + item.totalCost, 0) / filteredCosts.length
    : 0;
  const avgMarginRate = filteredCosts.length > 0
    ? filteredCosts.reduce((sum, item) => sum + item.marginRate, 0) / filteredCosts.length
    : 0;

  const getMarginColor = (rate: number) => {
    if (rate >= 15) return 'text-green-600';
    if (rate >= 10) return 'text-blue-600';
    if (rate >= 5) return 'text-orange-600';
    return 'text-red-600';
  };

  const columns: Column<CostData>[] = [
    {
      key: 'productCode',
      label: '제품코드'
    },
    {
      key: 'productName',
      label: '제품명'
    },
    {
      key: 'productType',
      label: '구분',
      render: (value) => (
        <Badge variant="outline">
          {value}
        </Badge>
      )
    },
    {
      key: 'materialCost',
      label: '재료비',
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    {
      key: 'laborCost',
      label: '인건비',
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    {
      key: 'totalCost',
      label: '총원가',
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    {
      key: 'standardPrice',
      label: '표준가격',
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    {
      key: 'marginRate',
      label: '마진율',
      render: (value, row) => {
        const rate = value as number;
        return (
          <span className={getMarginColor(rate)}>
            {rate.toFixed(1)}%
          </span>
        );
      }
    },
    {
      key: 'bomVersion',
      label: 'BOM 버전'
    }
  ];

  return (
    <ListPageTemplate
      title="원가 목록"
      description="BOM 및 생산 데이터 기반 제품별 원가를 관리합니다"
      icon={Calculator}
      stats={[
        {
          label: "평균 재료비",
          value: `${Math.round(avgMaterialCost).toLocaleString()}원`,
          icon: Package,
          iconColor: "text-blue-600",
          description: "제품당 평균"
        },
        {
          label: "평균 인건비",
          value: `${Math.round(avgLaborCost).toLocaleString()}원`,
          icon: TrendingUp,
          iconColor: "text-green-600",
          description: "제품당 평균"
        },
        {
          label: "평균 총원가",
          value: `${Math.round(avgTotalCost).toLocaleString()}원`,
          icon: Calculator,
          iconColor: "text-orange-600",
          description: "제품당 평균"
        },
        {
          label: "평균 마진율",
          value: `${avgMarginRate.toFixed(1)}%`,
          icon: DollarSign,
          iconColor: "text-purple-600",
          description: "수익성 지표"
        }
      ]}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="제품코드, 제품명 검색..."
      extraActions={
        <Select value={selectedType} onValueChange={setSelectedType}>
          <SelectTrigger className="w-[150px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {productTypes.map(type => (
              <SelectItem key={type} value={type}>{type}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      }
      data={filteredCosts}
      keyField="id"
      columns={columns}
      renderMobileCard={(cost) => ({
        title: cost.productName,
        subtitle: cost.productCode,
        badge: {
          label: cost.productType,
          variant: "outline"
        },
        fields: [
          {
            label: "재료비",
            value: `${cost.materialCost.toLocaleString()}원`
          },
          {
            label: "인건비",
            value: `${cost.laborCost.toLocaleString()}원`
          },
          {
            label: "총원가",
            value: `${cost.totalCost.toLocaleString()}원`
          },
          {
            label: "표준가격",
            value: `${cost.standardPrice.toLocaleString()}원`
          },
          {
            label: "마진율",
            value: `${cost.marginRate.toFixed(1)}%`,
            className: getMarginColor(cost.marginRate)
          },
          {
            label: "BOM 버전",
            value: cost.bomVersion
          }
        ]
      })}
      emptyIcon={Calculator}
      emptyTitle="원가 정보가 없습니다"
      emptyDescription="BOM 및 생산 데이터를 등록해주세요"
    />
  );
}
