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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { 
  Users, 
  Plus, 
  Edit, 
  Trash2,
  Eye,
  Phone,
  Mail,
  Calendar,
  Building,
  UserCheck,
  UserX
} from "lucide-react";

interface Employee {
  id: string;
  employeeNumber: string;
  name: string;
  department: string;
  position: string;
  email: string;
  phone: string;
  joinDate: string;
  status: "재직" | "휴직" | "퇴사";
}

export function EmployeeManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedDepartment, setSelectedDepartment] = useState("전체");
  const [selectedStatus, setSelectedStatus] = useState("전체");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null);

  // 모의 데이터
  const employees: Employee[] = [
    {
      id: "EMP001",
      employeeNumber: "2020-001",
      name: "김철수",
      department: "생산팀",
      position: "팀장",
      email: "kim.cs@company.com",
      phone: "010-1234-5678",
      joinDate: "2020-01-15",
      status: "재직"
    },
    {
      id: "EMP002",
      employeeNumber: "2021-015",
      name: "이영희",
      department: "품질팀",
      position: "과장",
      email: "lee.yh@company.com",
      phone: "010-2345-6789",
      joinDate: "2021-03-20",
      status: "재직"
    },
    {
      id: "EMP003",
      employeeNumber: "2019-008",
      name: "박민수",
      department: "자재팀",
      position: "대리",
      email: "park.ms@company.com",
      phone: "010-3456-7890",
      joinDate: "2019-06-10",
      status: "재직"
    },
    {
      id: "EMP004",
      employeeNumber: "2022-032",
      name: "정수진",
      department: "영업팀",
      position: "사원",
      email: "jung.sj@company.com",
      phone: "010-4567-8901",
      joinDate: "2022-08-01",
      status: "재직"
    },
    {
      id: "EMP005",
      employeeNumber: "2018-005",
      name: "최동훈",
      department: "생산팀",
      position: "부장",
      email: "choi.dh@company.com",
      phone: "010-5678-9012",
      joinDate: "2018-02-15",
      status: "휴직"
    }
  ];

  const departments = ["전체", "생산팀", "품질팀", "자재팀", "영업팀", "재무팀", "인사팀", "개발팀"];
  const positions = ["사원", "대리", "과장", "차장", "부장", "팀장", "이사"];

  const filteredEmployees = employees.filter(emp => {
    const matchesSearch = emp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         emp.employeeNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         emp.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesDepartment = selectedDepartment === "전체" || emp.department === selectedDepartment;
    const matchesStatus = selectedStatus === "전체" || emp.status === selectedStatus;
    return matchesSearch && matchesDepartment && matchesStatus;
  });

  const getStatusBadgeVariant = (status: string): "default" | "secondary" | "destructive" => {
    switch (status) {
      case "재직": return "default";
      case "휴직": return "secondary";
      case "퇴사": return "destructive";
      default: return "default";
    }
  };

  const handleEdit = (employee: Employee) => {
    setEditingEmployee(employee);
    setIsDialogOpen(true);
  };

  const handleAddNew = () => {
    setEditingEmployee(null);
    setIsDialogOpen(true);
  };

  const stats = [
    {
      label: "전체 사원",
      value: employees.length,
      icon: Users,
      iconColor: "text-blue-600"
    },
    {
      label: "재직",
      value: employees.filter(e => e.status === "재직").length,
      icon: UserCheck,
      iconColor: "text-green-600"
    },
    {
      label: "휴직",
      value: employees.filter(e => e.status === "휴직").length,
      icon: Users,
      iconColor: "text-orange-600"
    },
    {
      label: "퇴사",
      value: employees.filter(e => e.status === "퇴사").length,
      icon: UserX,
      iconColor: "text-red-600"
    }
  ];

  const columns: Column<Employee>[] = [
    {
      key: "employeeNumber",
      label: "사원번호",
      width: "120px"
    },
    {
      key: "name",
      label: "이름",
      render: (value, row) => (
        <div className="flex items-center gap-2">
          <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
            <span className="text-sm">{row.name[0]}</span>
          </div>
          {value}
        </div>
      )
    },
    {
      key: "department",
      label: "부서",
      render: (value) => (
        <div className="flex items-center gap-2">
          <Building className="h-4 w-4 text-muted-foreground" />
          {value}
        </div>
      )
    },
    {
      key: "position",
      label: "직급"
    },
    {
      key: "phone",
      label: "연락처",
      render: (value, row) => (
        <div className="space-y-1">
          <div className="flex items-center gap-2 text-sm">
            <Phone className="h-3 w-3 text-muted-foreground" />
            {value}
          </div>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Mail className="h-3 w-3" />
            {row.email}
          </div>
        </div>
      )
    },
    {
      key: "joinDate",
      label: "입사일",
      render: (value) => (
        <div className="flex items-center gap-2">
          <Calendar className="h-4 w-4 text-muted-foreground" />
          {value}
        </div>
      )
    },
    {
      key: "status",
      label: "상태",
      render: (value) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {value}
        </Badge>
      )
    },
    {
      key: "id",
      label: "작업",
      render: (value, row) => (
        <div className="flex gap-2">
          <Button variant="ghost" size="sm">
            <Eye className="h-4 w-4" />
          </Button>
          <Button variant="ghost" size="sm" onClick={() => handleEdit(row)}>
            <Edit className="h-4 w-4" />
          </Button>
          <Button variant="ghost" size="sm">
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      )
    }
  ];

  const extraActions = (
    <>
      <Select value={selectedDepartment} onValueChange={setSelectedDepartment}>
        <SelectTrigger className="w-[120px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {departments.map((dept) => (
            <SelectItem key={dept} value={dept}>
              {dept}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Select value={selectedStatus} onValueChange={setSelectedStatus}>
        <SelectTrigger className="w-[100px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {["전체", "재직", "휴직", "퇴사"].map((status) => (
            <SelectItem key={status} value={status}>
              {status}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </>
  );

  return (
    <>
      <ListPageTemplate
        title="사원 목록"
        description="사원 정보를 등록하고 관리합니다"
        icon={Users}
        actions={
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button onClick={handleAddNew}>
                <Plus className="h-4 w-4 mr-2" />
                사원 등록
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>{editingEmployee ? "사원 정보 수정" : "신규 사원 등록"}</DialogTitle>
                <DialogDescription>
                  {editingEmployee ? "사원 정보를 수정합니다." : "새로운 사원을 등록합니다."}
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="employeeNumber">사원번호</Label>
                    <Input
                      id="employeeNumber"
                      placeholder="2025-001"
                      defaultValue={editingEmployee?.employeeNumber}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="name">이름</Label>
                    <Input
                      id="name"
                      placeholder="홍길동"
                      defaultValue={editingEmployee?.name}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="department">부서</Label>
                    <Select defaultValue={editingEmployee?.department}>
                      <SelectTrigger id="department">
                        <SelectValue placeholder="부서 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {departments.filter(d => d !== "전체").map((dept) => (
                          <SelectItem key={dept} value={dept}>
                            {dept}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="position">직급</Label>
                    <Select defaultValue={editingEmployee?.position}>
                      <SelectTrigger id="position">
                        <SelectValue placeholder="직급 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {positions.map((pos) => (
                          <SelectItem key={pos} value={pos}>
                            {pos}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="email">이메일</Label>
                    <Input
                      id="email"
                      type="email"
                      placeholder="example@company.com"
                      defaultValue={editingEmployee?.email}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone">연락처</Label>
                    <Input
                      id="phone"
                      placeholder="010-0000-0000"
                      defaultValue={editingEmployee?.phone}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="joinDate">입사일</Label>
                    <Input
                      id="joinDate"
                      type="date"
                      defaultValue={editingEmployee?.joinDate}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="status">재직 상태</Label>
                    <Select defaultValue={editingEmployee?.status || "재직"}>
                      <SelectTrigger id="status">
                        <SelectValue placeholder="상태 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="재직">재직</SelectItem>
                        <SelectItem value="휴직">휴직</SelectItem>
                        <SelectItem value="퇴사">퇴사</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex justify-end gap-2 pt-4">
                  <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                    취소
                  </Button>
                  <Button onClick={() => setIsDialogOpen(false)}>
                    {editingEmployee ? "수정" : "등록"}
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        }
        stats={stats}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="이름, 사원번호, 이메일로 검색..."
        filterButton={false}
        extraActions={extraActions}
        data={filteredEmployees}
        keyField="id"
        columns={columns}
        renderMobileCard={(employee) => ({
          title: employee.name,
          subtitle: employee.employeeNumber,
          icon: (
            <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
              <span>{employee.name[0]}</span>
            </div>
          ),
          badge: {
            label: employee.status,
            variant: getStatusBadgeVariant(employee.status)
          },
          fields: [
            {
              label: "부서",
              value: `${employee.department} · ${employee.position}`
            },
            {
              label: "연락처",
              value: employee.phone
            },
            {
              label: "이메일",
              value: employee.email
            },
            {
              label: "입사일",
              value: employee.joinDate
            }
          ],
          actions: [
            {
              label: "보기",
              onClick: () => {},
              icon: Eye,
              variant: "outline" as const
            },
            {
              label: "수정",
              onClick: () => handleEdit(employee),
              icon: Edit,
              variant: "outline" as const
            }
          ]
        })}
        emptyIcon={Users}
        emptyTitle="등록된 사원이 없습니다"
        emptyDescription="새로운 사원을 등록해주세요"
      />
    </>
  );
}