'use client';

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

import { UserManagementHeader } from './components/UserManagementHeader';
import { UserManagementStatsCards } from './components/UserManagementStatsCards';
import { UserManagementFilters } from './components/UserManagementFilters';
import { UserList } from './components/UserList';
import { UserFormDialog } from './components/UserFormDialog';
import { UserDetailDialog } from './components/UserDetailDialog';
import { User, Enterprise, UserFilters, UserFormData } from './types';

export default function TenantUserManagementPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [filters, setFilters] = useState<UserFilters>({
    searchKeyword: '',
    statusFilter: 'all',
    typeFilter: 'all'
  });
  const [showForm, setShowForm] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [formData, setFormData] = useState<UserFormData>({
    userType: 'enterprise_admin',
    status: 'active',
    roleIds: [],
  });

  useEffect(() => {
    loadUsers();
    loadEnterprises();
  }, []);

  const loadEnterprises = () => {
    const data = localStorage.getItem('smart_agriculture_enterprises');
    if (data) {
      const allEnterprises = JSON.parse(data);
      setEnterprises(allEnterprises.map((e: any) => ({ id: e.id, name: e.name })));
    }
  };

  const loadUsers = () => {
    const data = localStorage.getItem('smart_agriculture_users');
    if (data) {
      setUsers(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockUsers: User[] = [
        {
          id: 'user-1',
          username: 'admin',
          name: '系统管理员',
          phone: '13900000000',
          email: 'admin@system.com',
          userType: 'super_admin',
          roleIds: ['role-1'],
          roles: ['超级管理员'],
          status: 'active',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          lastLoginTime: '2024-10-14T10:00:00',
        },
        {
          id: 'user-2',
          username: 'ent_admin_1',
          name: '李总',
          phone: '13900139002',
          email: 'litotal@fengshou.com',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          userType: 'enterprise_admin',
          roleIds: ['role-2'],
          roles: ['企业管理员'],
          status: 'active',
          createdAt: '2024-10-05T10:00:00',
          updatedAt: '2024-10-05T10:00:00',
          lastLoginTime: '2024-10-14T09:00:00',
        },
        {
          id: 'user-3',
          username: 'zhangsan',
          name: '张三',
          phone: '13800138001',
          email: 'zhangsan@fengshou.com',
          enterpriseId: 'ent-2',
          enterpriseName: '丰收现代农业集团',
          userType: 'employee',
          roleIds: ['role-3'],
          roles: ['操作员'],
          status: 'active',
          createdAt: '2024-10-01T08:00:00',
          updatedAt: '2024-10-01T08:00:00',
          lastLoginTime: '2024-10-14T08:30:00',
        },
      ];
      localStorage.setItem('smart_agriculture_users', JSON.stringify(mockUsers));
      setUsers(mockUsers);
    }
  };

  const filteredUsers = users.filter(user => {
    const matchKeyword = !filters.searchKeyword ||
      user.name.includes(filters.searchKeyword) ||
      user.username.includes(filters.searchKeyword) ||
      user.phone.includes(filters.searchKeyword) ||
      (user.enterpriseName && user.enterpriseName.includes(filters.searchKeyword));

    const matchStatus = filters.statusFilter === 'all' || user.status === filters.statusFilter;
    const matchType = filters.typeFilter === 'all' || user.userType === filters.typeFilter;

    return matchKeyword && matchStatus && matchType;
  });

  const handleAddUser = () => {
    setEditingUser(null);
    setFormData({
      userType: 'enterprise_admin',
      status: 'active',
      roleIds: [],
    });
    setShowForm(true);
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormData(user);
    setShowForm(true);
  };

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

    // 如果是企业管理员，必须选择企业
    if (formData.userType === 'enterprise_admin' && !formData.enterpriseId) {
      toast.error('企业管理员必须选择所属企业');
      return;
    }

    // 根据选择的企业ID设置企业名称
    let enterpriseName = formData.enterpriseName;
    if (formData.enterpriseId && !enterpriseName) {
      const selectedEnterprise = enterprises.find(e => e.id === formData.enterpriseId);
      if (selectedEnterprise) {
        enterpriseName = selectedEnterprise.name;
      }
    }

    if (editingUser) {
      const updated = users.map(user =>
        user.id === editingUser.id
          ? {
              ...user,
              ...formData,
              enterpriseName,
              updatedAt: new Date().toISOString(),
            }
          : user
      );
      setUsers(updated);
      localStorage.setItem('smart_agriculture_users', JSON.stringify(updated));
      toast.success('用户信息更新成功');
    } else {
      const newUser: User = {
        id: `user-${Date.now()}`,
        ...formData as User,
        enterpriseName,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      const updated = [...users, newUser];
      setUsers(updated);
      localStorage.setItem('smart_agriculture_users', JSON.stringify(updated));
      toast.success('用户添加成功');
    }

    setShowForm(false);
  };

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

    const updated = users.filter(user => user.id !== id);
    setUsers(updated);
    localStorage.setItem('smart_agriculture_users', JSON.stringify(updated));
    toast.success('用户删除成功');
  };

  const handleToggleStatus = (user: User) => {
    const newStatus = user.status === 'active' ? 'frozen' : 'active';
    const updated = users.map(u =>
      u.id === user.id
        ? { ...u, status: newStatus, updatedAt: new Date().toISOString() }
        : u
    );
    setUsers(updated);
    localStorage.setItem('smart_agriculture_users', JSON.stringify(updated));
    toast.success(newStatus === 'active' ? '账户已激活' : '账户已冻结');
  };

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

  const handleViewDetail = (user: User) => {
    setSelectedUser(user);
    setShowDetailDialog(true);
  };

  const handleExport = () => {
    const dataStr = JSON.stringify(users, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `users_${new Date().getTime()}.json`;
    link.click();
    toast.success('用户数据导出成功');
  };

  return (
    <div className="space-y-6">
      <UserManagementHeader
        onAddUser={handleAddUser}
        onExport={handleExport}
      />

      {/* 统计卡片 */}
      <UserManagementStatsCards users={users} />

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

      {/* 用户列表 */}
      <UserList
        users={filteredUsers}
        onViewDetail={handleViewDetail}
        onEdit={handleEdit}
        onResetPassword={handleResetPassword}
        onToggleStatus={handleToggleStatus}
        onDelete={handleDelete}
      />

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

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