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 { Calendar } from "./ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { 
  Calendar as CalendarIcon, 
  Clock,
  Users, 
  CheckCircle,
  XCircle,
  AlertTriangle,
  Download
} from "lucide-react";
import { format } from "date-fns";
import { ko } from "date-fns/locale";

interface AttendanceRecord {
  id: string;
  employeeId: string;
  employeeName: string;
  department: string;
  date: string;
  checkIn: string;
  checkOut: string;
  status: "정상" | "지각" | "조퇴" | "결근" | "휴가";
  workHours: number;
  overtime: number;
}

export function AttendanceManagement() {
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedDepartment, setSelectedDepartment] = useState("all");

  const attendanceData: AttendanceRecord[] = [
    {
      id: "1",
      employeeId: "EMP001",
      employeeName: "김대표",
      department: "경영진",
      date: "2025-10-22",
      checkIn: "08:45",
      checkOut: "18:30",
      status: "정상",
      workHours: 9.75,
      overtime: 1.5
    },
    {
      id: "2",
      employeeId: "EMP002",
      employeeName: "이생산",
      department: "생산부",
      date: "2025-10-22",
      checkIn: "08:50",
      checkOut: "18:00",
      status: "정상",
      workHours: 9.17,
      overtime: 1.0
    },
    {
      id: "3",
      employeeId: "EMP003",
      employeeName: "박품질",
      department: "품질부",
      date: "2025-10-22",
      checkIn: "09:15",
      checkOut: "18:00",
      status: "지각",
      workHours: 8.75,
      overtime: 0
    },
    {
      id: "4",
      employeeId: "EMP004",
      employeeName: "정영업",
      department: "영업부",
      date: "2025-10-22",
      checkIn: "08:55",
      checkOut: "17:30",
      status: "조퇴",
      workHours: 8.58,
      overtime: 0
    },
    {
      id: "5",
      employeeId: "EMP005",
      employeeName: "최자재",
      department: "자재부",
      date: "2025-10-22",
      checkIn: "-",
      checkOut: "-",
      status: "휴가",
      workHours: 0,
      overtime: 0
    }
  ];

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

  const totalEmployees = 60;
  const normalCount = filteredData.filter(r => r.status === "정상").length;
  const lateCount = filteredData.filter(r => r.status === "지각").length;
  const absentCount = filteredData.filter(r => r.status === "결근").length;
  const leaveCount = filteredData.filter(r => r.status === "휴가").length;

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

  const columns: Column<AttendanceRecord>[] = [
    {
      key: "employeeId",
      label: "사번"
    },
    {
      key: "employeeName",
      label: "이름"
    },
    {
      key: "department",
      label: "부서"
    },
    {
      key: "checkIn",
      label: "출근시간"
    },
    {
      key: "checkOut",
      label: "퇴근시간"
    },
    {
      key: "workHours",
      label: "근무시간",
      render: (value) => `${(value as number).toFixed(2)}시간`
    },
    {
      key: "overtime",
      label: "연장근무",
      render: (value) => {
        const hours = value as number;
        return hours > 0 ? `${hours.toFixed(1)}시간` : "-";
      }
    },
    {
      key: "status",
      label: "상태",
      render: (value) => {
        const status = value as string;
        const variantMap: Record<string, "default" | "destructive" | "secondary" | "outline"> = {
          "정상": "default",
          "지각": "secondary",
          "조퇴": "secondary",
          "결근": "destructive",
          "휴가": "outline"
        };
        return <Badge variant={variantMap[status] || "outline"}>{status}</Badge>;
      }
    }
  ];

  return (
    <ListPageTemplate
      title="근태 목록"
      description="직원 출퇴근 및 근무시간을 관리합니다"
      icon={Clock}
      stats={[
        {
          label: "전체 인원",
          value: `${totalEmployees}명`,
          icon: Users,
          iconColor: "text-blue-600",
          description: "등록된 직원"
        },
        {
          label: "정상 출근",
          value: `${normalCount}명`,
          icon: CheckCircle,
          iconColor: "text-green-600",
          description: "91.7% 출근율"
        },
        {
          label: "지각",
          value: `${lateCount}명`,
          icon: AlertTriangle,
          iconColor: "text-yellow-600",
          description: "5.0%"
        },
        {
          label: "결근",
          value: `${absentCount}명`,
          icon: XCircle,
          iconColor: "text-red-600",
          description: "0%"
        }
      ]}
      actions={
        <>
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline">
                <CalendarIcon className="w-4 h-4 mr-2" />
                {format(selectedDate, "PPP", { locale: ko })}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <Calendar
                mode="single"
                selected={selectedDate}
                onSelect={(date) => date && setSelectedDate(date)}
                locale={ko}
              />
            </PopoverContent>
          </Popover>
          <Button>
            <Download className="w-4 h-4 mr-2" />
            엑셀 다운로드
          </Button>
        </>
      }
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="사번, 이름 검색..."
      extraActions={
        <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.department}`,
        badge: {
          label: record.status,
          variant: record.status === "정상" ? "default" : record.status === "결근" ? "destructive" : "secondary"
        },
        fields: [
          {
            label: "출근시간",
            value: record.checkIn
          },
          {
            label: "퇴근시간",
            value: record.checkOut
          },
          {
            label: "근무시간",
            value: `${record.workHours.toFixed(2)}시간`
          },
          {
            label: "연장근무",
            value: record.overtime > 0 ? `${record.overtime.toFixed(1)}시간` : "-"
          }
        ]
      })}
      emptyIcon={Clock}
      emptyTitle="근태 정보가 없습니다"
      emptyDescription="근태 데이터를 등록해주세요"
    />
  );
}
