'use client';

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

import { RoleManagementHeader } from './components/RoleManagementHeader';
import { RoleManagementStatsCards } from './components/RoleManagementStatsCards';
import { RoleSearch } from './components/RoleSearch';
import { RoleList } from './components/RoleList';
import { RoleFormDialog } from './components/RoleFormDialog';
import { RoleDetailDialog } from './components/RoleDetailDialog';
import { RoleManagementInstructions } from './components/RoleManagementInstructions';
import { Role, RoleFormData } from './types';

export default function RoleManagementPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [formData, setFormData] = useState<RoleFormData>({
    type: 'custom',
    status: 'active',
    menuIds: [],
    permissionIds: [],
  });

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

  const loadRoles = () => {
    const data = localStorage.getItem('smart_agriculture_roles');
    if (data) {
      setRoles(JSON.parse(data));
    } else {
      const mockRoles: Role[] = [
        {
          id: 'role-1',
          name: '超级管理员',
          code: 'super_admin',
          description: '系统最高权限，可管理所有功能和数据',
          type: 'system',
          menuIds: ['*'],
          permissionIds: ['*'],
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-2',
          name: '企业管理员',
          code: 'enterprise_admin',
          description: '企业管理员，可管理本企业的员工和数据',
          type: 'system',
          menuIds: ['config-user', 'machinery', 'field'],
          permissionIds: ['user:view', 'user:add', 'user:edit', 'machinery:*'],
          defaultHomePage: '/machinery/archive/entry',
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-3',
          name: '操作员',
          code: 'operator',
          description: '一般操作员，可查看和操作农机设备',
          type: 'system',
          menuIds: ['machinery', 'field'],
          permissionIds: ['machinery:view', 'machinery:control', 'field:view'],
          defaultHomePage: '/machinery/monitoring/location',
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'role-4',
          name: '维修员',
          code: 'maintenance',
          description: '农机维修人员，负责设备维护和故障诊断',
          type: 'custom',
          menuIds: ['machinery-fault', 'machinery-archive'],
          permissionIds: ['machinery:view', 'fault:view', 'fault:handle'],
          status: 'active',
          createdAt: '2024-10-01T00:00:00',
          updatedAt: '2024-10-01T00:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(mockRoles));
      setRoles(mockRoles);
    }
  };

  const filteredRoles = roles.filter(role => {
    const matchKeyword = !searchKeyword ||
      role.name.includes(searchKeyword) ||
      role.code.includes(searchKeyword) ||
      (role.description && role.description.includes(searchKeyword));
    return matchKeyword;
  });

  const handleAddRole = () => {
    setEditingRole(null);
    setFormData({
      type: 'custom',
      status: 'active',
      menuIds: [],
      permissionIds: [],
    });
    setShowForm(true);
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setFormData(role);
    setShowForm(true);
  };

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

    if (editingRole) {
      const updated = roles.map(role =>
        role.id === editingRole.id
          ? {
              ...role,
              ...formData,
              updatedAt: new Date().toISOString(),
            }
          : role
      );
      setRoles(updated);
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
      toast.success('角色更新成功');
    } else {
      const newRole: Role = {
        id: `role-${Date.now()}`,
        ...formData as Role,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...roles, newRole];
      setRoles(updated);
      localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
      toast.success('角色添加成功');
    }

    setShowForm(false);
  };

  const handleDelete = (id: string) => {
    const role = roles.find(r => r.id === id);
    if (role && role.type === 'system') {
      toast.error('系统角色不能删除');
      return;
    }

    if (!confirm('确定要删除该角色吗？')) return;

    const updated = roles.filter(role => role.id !== id);
    setRoles(updated);
    localStorage.setItem('smart_agriculture_roles', JSON.stringify(updated));
    toast.success('角色删除成功');
  };

  const handleViewDetail = (role: Role) => {
    setSelectedRole(role);
    setShowDetailDialog(true);
  };

  return (
    <div className="space-y-6">
      <RoleManagementHeader
        onAddRole={handleAddRole}
      />

      {/* 统计卡片 */}
      <RoleManagementStatsCards roles={roles} />

      {/* 搜索 */}
      <RoleSearch
        searchKeyword={searchKeyword}
        onSearchChange={setSearchKeyword}
      />

      {/* 角色列表 */}
      <RoleList
        roles={filteredRoles}
        onViewDetail={handleViewDetail}
        onEdit={handleEdit}
        onDelete={handleDelete}
      />

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

      {/* 详情对话框 */}
      <RoleDetailDialog
        open={showDetailDialog}
        onOpenChange={setShowDetailDialog}
        selectedRole={selectedRole}
      />

      {/* 使用说明 */}
      <RoleManagementInstructions />
    </div>
  );
}