'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';

import { EmployeeManagementHeader } from './components/EmployeeManagementHeader';
import { EmployeeManagementStatsCards } from './components/EmployeeManagementStatsCards';
import { EmployeeManagementFilters } from './components/EmployeeManagementFilters';
import { EmployeeList } from './components/EmployeeList';
import { EmployeeFormDialog } from './components/EmployeeFormDialog';
import { EmployeeDetailDialog } from './components/EmployeeDetailDialog';
import { Employee, Role, EmployeeFilters, EmployeeFormData } from './types';

export default function EmployeeManagementPage() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [filters, setFilters] = useState<EmployeeFilters>({
    searchKeyword: '',
    statusFilter: 'all'
  });
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null);
  const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(null);
  const [formData, setFormData] = useState<EmployeeFormData>({
    enterpriseId: 'ent-2',
    enterpriseName: '丰收现代农业集团',
    status: 'active',
    roleIds: [],
  });

  useEffect(() => {
    loadEmployees();
    loadRoles();
  }, []);

  const loadRoles = () => {
    const data = localStorage.getItem('smart_agriculture_roles');
    if (data) {
      setRoles(JSON.parse(data));
    }
  };

  const loadEmployees = () => {
    const data = localStorage.getItem('smart_agriculture_employees');
    if (data) {
      setEmployees(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockEmployees: Employee[] = [
        {
          id: 'emp-1',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'zhangsan',
          name: '张三',
          phone: '13800138001',
          email: 'zhangsan@example.com',
          department: '技术部',
          position: '农机操作员',
          roleIds: ['role-3'],
          roles: ['操作员'],
          status: 'active',
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          lastLoginTime: '2024-10-14T09:30:00',
        },
        {
          id: 'emp-2',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'lisi',
          name: '李四',
          phone: '13900139002',
          email: 'lisi@example.com',
          department: '管理部',
          position: '部门主管',
          roleIds: ['role-2'],
          roles: ['企业管理员'],
          status: 'active',
          createdAt: '2024-10-02T10:00:00',
          updatedAt: '2024-10-02T10:00:00',
          lastLoginTime: '2024-10-14T08:15:00',
        },
        {
          id: 'emp-3',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          username: 'wangwu',
          name: '王五',
          phone: '13700137003',
          department: '维修部',
          position: '维修技师',
          roleIds: ['role-3'],
          roles: ['操作员'],
          status: 'frozen',
          createdAt: '2024-09-28T14:00:00',
          updatedAt: '2024-10-10T16:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(mockEmployees));
      setEmployees(mockEmployees);
    }
  };

  const filteredEmployees = employees.filter(emp => {
    const matchKeyword = !filters.searchKeyword ||
      emp.name.includes(filters.searchKeyword) ||
      emp.username.includes(filters.searchKeyword) ||
      emp.phone.includes(filters.searchKeyword) ||
      (emp.department && emp.department.includes(filters.searchKeyword));

    const matchStatus = filters.statusFilter === 'all' || emp.status === filters.statusFilter;

    return matchKeyword && matchStatus;
  });

  const handleAddEmployee = () => {
    setEditingEmployee(null);
    setFormData({
      enterpriseId: 'ent-2',
      enterpriseName: '丰收现代农业集团',
      status: 'active',
      roleIds: [],
    });
    setShowForm(true);
  };

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

  const handleSave = () => {
    if (!formData.username || !formData.name || !formData.phone) {
      toast.error('请填写必填项');
      return;
    }

    // 验证角色选择
    if (!formData.roleIds || formData.roleIds.length === 0) {
      toast.error('请至少选择一个角色');
      return;
    }

    // 根据角色ID设置角色名称
    const selectedRoles = roles.filter(r => formData.roleIds?.includes(r.id));
    const roleNames = selectedRoles.map(r => r.name);

    if (editingEmployee) {
      // 更新
      const updated = employees.map(emp =>
        emp.id === editingEmployee.id
          ? {
              ...emp,
              ...formData,
              roles: roleNames,
              updatedAt: new Date().toISOString(),
            }
          : emp
      );
      setEmployees(updated);
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
      toast.success('员工信息更新成功');
    } else {
      // 新增
      const newEmployee: Employee = {
        id: `emp-${Date.now()}`,
        ...formData as Employee,
        roles: roleNames,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...employees, newEmployee];
      setEmployees(updated);
      localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
      toast.success('员工添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    if (!confirm('确定要删除该员工吗？')) return;

    const updated = employees.filter(emp => emp.id !== id);
    setEmployees(updated);
    localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
    toast.success('员工删除成功');
  };

  const handleToggleStatus = (employee: Employee) => {
    const newStatus = employee.status === 'active' ? 'frozen' : 'active';
    const updated = employees.map(emp =>
      emp.id === employee.id
        ? { ...emp, status: newStatus, updatedAt: new Date().toISOString() }
        : emp
    );
    setEmployees(updated);
    localStorage.setItem('smart_agriculture_employees', JSON.stringify(updated));
    toast.success(newStatus === 'active' ? '账户已激活' : '账户已冻结');
  };

  const handleResetPassword = (employee: Employee) => {
    if (!confirm(`确定要重置 ${employee.name} 的密码吗？`)) return;
    toast.success('密码已重置为：123456');
  };

  const handleViewDetail = (employee: Employee) => {
    setSelectedEmployee(employee);
    setShowDetailDialog(true);
  };

  return (
    <div className="space-y-6">
      <EmployeeManagementHeader
        onAddEmployee={handleAddEmployee}
      />

      {/* 统计卡片 */}
      <EmployeeManagementStatsCards employees={employees} />

      {/* 搜索和筛选 */}
      <EmployeeManagementFilters
        filters={filters}
        onFiltersChange={setFilters}
      />

      {/* 员工列表 */}
      <EmployeeList
        employees={filteredEmployees}
        onViewDetail={handleViewDetail}
        onEdit={handleEdit}
        onResetPassword={handleResetPassword}
        onToggleStatus={handleToggleStatus}
        onDelete={handleDelete}
      />

      {/* 添加/编辑表单 */}
      <EmployeeFormDialog
        open={showForm}
        onOpenChange={setShowForm}
        editingEmployee={editingEmployee}
        formData={formData}
        onFormDataChange={setFormData}
        onSave={handleSave}
        roles={roles}
      />

      {/* 详情对话框 */}
      <EmployeeDetailDialog
        open={showDetailDialog}
        onOpenChange={setShowDetailDialog}
        selectedEmployee={selectedEmployee}
      />
    </div>
  );
}