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 { 
  DollarSign, 
  TrendingUp,
  Users, 
  Download,
  Calculator,
  Calendar,
  Award
} from "lucide-react";

interface PayrollRecord {
  id: string;
  employeeId: string;
  employeeName: string;
  department: string;
  position: string;
  baseSalary: number;
  allowances: number;
  overtime: number;
  bonus: number;
  deductions: number;
  netSalary: number;
  status: "지급완료" | "지급예정" | "보류";
}

export function PayrollManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedDepartment, setSelectedDepartment] = useState("all");
  const [selectedMonth, setSelectedMonth] = useState("2025-10");

  const payrollData: PayrollRecord[] = [
    {
      id: "1",
      employeeId: "EMP001",
      employeeName: "김대표",
      department: "경영진",
      position: "대표이사",
      baseSalary: 10000000,
      allowances: 1000000,
      overtime: 0,
      bonus: 2000000,
      deductions: 2600000,
      netSalary: 10400000,
      status: "지급완료"
    },
    {
      id: "2",
      employeeId: "EMP002",
      employeeName: "이생산",
      department: "생산부",
      position: "과장",
      baseSalary: 5500000,
      allowances: 300000,
      overtime: 500000,
      bonus: 1000000,
      deductions: 1480000,
      netSalary: 5820000,
      status: "지급완료"
    },
    {
      id: "3",
      employeeId: "EMP003",
      employeeName: "박품질",
      department: "품질부",
      position: "대리",
      baseSalary: 4800000,
      allowances: 200000,
      overtime: 300000,
      bonus: 800000,
      deductions: 1224000,
      netSalary: 4876000,
      status: "지급완료"
    },
    {
      id: "4",
      employeeId: "EMP004",
      employeeName: "정영업",
      department: "영업부",
      position: "차장",
      baseSalary: 6200000,
      allowances: 400000,
      overtime: 200000,
      bonus: 1200000,
      deductions: 1620000,
      netSalary: 6380000,
      status: "지급예정"
    },
    {
      id: "5",
      employeeId: "EMP005",
      employeeName: "최자재",
      department: "자재부",
      position: "주임",
      baseSalary: 4200000,
      allowances: 150000,
      overtime: 400000,
      bonus: 600000,
      deductions: 1070000,
      netSalary: 4280000,
      status: "지급예정"
    }
  ];

  const formatCurrency = (amount: number) => {
    return amount.toLocaleString('ko-KR') + '원';
  };

  const filteredData = payrollData.filter(record => {
    const matchesSearch = record.employeeName.includes(searchTerm) || record.employeeId.includes(searchTerm);
    const matchesDepartment = selectedDepartment === "all" || record.department === selectedDepartment;
    return matchesSearch && matchesDepartment;
  });

  const totalPayroll = filteredData.reduce((sum, record) => sum + record.netSalary, 0);
  const totalBase = filteredData.reduce((sum, record) => sum + record.baseSalary, 0);
  const totalBonus = filteredData.reduce((sum, record) => sum + record.bonus, 0);
  const totalDeductions = filteredData.reduce((sum, record) => sum + record.deductions, 0);

  const departments = ["all", ...Array.from(new Set(payrollData.map(p => p.department)))];

  const columns: Column<PayrollRecord>[] = [
    {
      key: "employeeId",
      label: "사번"
    },
    {
      key: "employeeName",
      label: "이름"
    },
    {
      key: "department",
      label: "부서"
    },
    {
      key: "position",
      label: "직급"
    },
    {
      key: "baseSalary",
      label: "기본급",
      render: (value) => formatCurrency(value as number)
    },
    {
      key: "allowances",
      label: "수당",
      render: (value) => formatCurrency(value as number)
    },
    {
      key: "overtime",
      label: "초과근무",
      render: (value) => formatCurrency(value as number)
    },
    {
      key: "bonus",
      label: "상여",
      render: (value) => formatCurrency(value as number)
    },
    {
      key: "deductions",
      label: "공제",
      render: (value) => formatCurrency(value as number)
    },
    {
      key: "netSalary",
      label: "실지급액",
      render: (value) => (
        <span className="font-semibold">
          {formatCurrency(value as number)}
        </span>
      )
    },
    {
      key: "status",
      label: "상태",
      render: (value) => {
        const status = value as string;
        const variant = status === "지급완료" ? "default" : status === "지급예정" ? "secondary" : "destructive";
        return <Badge variant={variant}>{status}</Badge>;
      }
    }
  ];

  return (
    <ListPageTemplate
      title="급여 목록"
      description="직원 급여 및 수당을 관리합니다"
      icon={DollarSign}
      stats={[
        {
          label: "총 지급액",
          value: formatCurrency(totalPayroll),
          icon: DollarSign,
          iconColor: "text-blue-600",
          description: "전월 대비 +5.2%"
        },
        {
          label: "기본급 총액",
          value: formatCurrency(totalBase),
          icon: Calculator,
          iconColor: "text-green-600",
          description: `${filteredData.length}명`
        },
        {
          label: "상여 총액",
          value: formatCurrency(totalBonus),
          icon: Award,
          iconColor: "text-purple-600",
          description: "성과급 포함"
        },
        {
          label: "공제 총액",
          value: formatCurrency(totalDeductions),
          icon: TrendingUp,
          iconColor: "text-orange-600",
          description: "4대보험+세금"
        }
      ]}
      actions={
        <Button>
          <Download className="w-4 h-4 mr-2" />
          급여명세서
        </Button>
      }
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="사번, 이름 검색..."
      extraActions={
        <>
          <Select value={selectedMonth} onValueChange={setSelectedMonth}>
            <SelectTrigger className="w-[150px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="2025-10">2025년 10월</SelectItem>
              <SelectItem value="2025-09">2025년 9월</SelectItem>
              <SelectItem value="2025-08">2025년 8월</SelectItem>
              <SelectItem value="2025-07">2025년 7월</SelectItem>
            </SelectContent>
          </Select>
          <Select value={selectedDepartment} onValueChange={setSelectedDepartment}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="부서 선택" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 부서</SelectItem>
              {departments.filter(d => d !== "all").map(dept => (
                <SelectItem key={dept} value={dept}>{dept}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </>
      }
      data={filteredData}
      keyField="id"
      columns={columns}
      renderMobileCard={(record) => ({
        title: record.employeeName,
        subtitle: `${record.employeeId} | ${record.position}`,
        badge: {
          label: record.status,
          variant: record.status === "지급완료" ? "default" : record.status === "지급예정" ? "secondary" : "destructive"
        },
        fields: [
          {
            label: "부서",
            value: record.department
          },
          {
            label: "기본급",
            value: formatCurrency(record.baseSalary)
          },
          {
            label: "수당",
            value: formatCurrency(record.allowances)
          },
          {
            label: "초과근무",
            value: formatCurrency(record.overtime)
          },
          {
            label: "상여",
            value: formatCurrency(record.bonus)
          },
          {
            label: "공제",
            value: formatCurrency(record.deductions)
          },
          {
            label: "실지급액",
            value: formatCurrency(record.netSalary),
            className: "font-semibold"
          }
        ]
      })}
      emptyIcon={DollarSign}
      emptyTitle="급여 정보가 없습니다"
      emptyDescription="급여 데이터를 등록해주세요"
    />
  );
}
