import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { User } from '../../types/user-management';
import { Search, Plus, Edit, Trash2, Lock, Eye, UserX, UserCheck, Download, Upload } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface Enterprise {
  id: string;
  name: string;
}

export function UserManagement() {
  const [users, setUsers] = useState<User[]>([]);
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('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<Partial<User>>({
    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 = !searchKeyword ||
      user.name.includes(searchKeyword) ||
      user.username.includes(searchKeyword) ||
      user.phone.includes(searchKeyword) ||
      (user.enterpriseName && user.enterpriseName.includes(searchKeyword));

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

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

  const handleAdd = () => {
    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('用户数据导出成功');
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge className="bg-green-100 text-green-700">正常</Badge>;
      case 'frozen':
        return <Badge className="bg-gray-100 text-gray-700">已冻结</Badge>;
      case 'inactive':
        return <Badge className="bg-red-100 text-red-700">停用</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getUserTypeBadge = (type: string) => {
    switch (type) {
      case 'super_admin':
        return <Badge className="bg-purple-100 text-purple-700">超级管理员</Badge>;
      case 'enterprise_admin':
        return <Badge className="bg-blue-100 text-blue-700">企业管理员</Badge>;
      case 'employee':
        return <Badge className="bg-green-100 text-green-700">员工</Badge>;
      default:
        return <Badge>{type}</Badge>;
    }
  };

  const stats = [
    {
      label: '总用户数',
      value: users.length,
      color: 'text-blue-600',
      bg: 'bg-blue-100',
    },
    {
      label: '超级管理员',
      value: users.filter(u => u.userType === 'super_admin').length,
      color: 'text-purple-600',
      bg: 'bg-purple-100',
    },
    {
      label: '企业管理员',
      value: users.filter(u => u.userType === 'enterprise_admin').length,
      color: 'text-blue-600',
      bg: 'bg-blue-100',
    },
    {
      label: '正常用户',
      value: users.filter(u => u.status === 'active').length,
      color: 'text-green-600',
      bg: 'bg-green-100',
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">用户管理</h2>
          <p className="text-muted-foreground">平台所有用户账户的集中管理</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExport}>
            <Download className="w-4 h-4 mr-2" />
            导出
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            添加用户
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className="p-4">
            <div className="text-sm text-muted-foreground">{stat.label}</div>
            <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
          </Card>
        ))}
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索用户名、姓名、电话、企业..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="super_admin">超级管理员</SelectItem>
              <SelectItem value="enterprise_admin">企业管理员</SelectItem>
              <SelectItem value="employee">员工</SelectItem>
            </SelectContent>
          </Select>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="active">正常</SelectItem>
              <SelectItem value="frozen">已冻结</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 用户列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>用户名</TableHead>
              <TableHead>姓名</TableHead>
              <TableHead>电话</TableHead>
              <TableHead>所属企业</TableHead>
              <TableHead>用户类型</TableHead>
              <TableHead>角色</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredUsers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              filteredUsers.map((user) => (
                <TableRow key={user.id}>
                  <TableCell className="text-muted-foreground">{user.username}</TableCell>
                  <TableCell>{user.name}</TableCell>
                  <TableCell>{user.phone}</TableCell>
                  <TableCell className="text-muted-foreground">{user.enterpriseName || '-'}</TableCell>
                  <TableCell>{getUserTypeBadge(user.userType)}</TableCell>
                  <TableCell>
                    {user.roles && user.roles.length > 0 ? user.roles.join(', ') : '-'}
                  </TableCell>
                  <TableCell>{getStatusBadge(user.status)}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(user)}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(user)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleResetPassword(user)}
                      >
                        <Lock className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleToggleStatus(user)}
                      >
                        {user.status === 'active' ? (
                          <UserX className="w-4 h-4 text-orange-600" />
                        ) : (
                          <UserCheck className="w-4 h-4 text-green-600" />
                        )}
                      </Button>
                      {user.userType !== 'super_admin' && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(user.id)}
                        >
                          <Trash2 className="w-4 h-4 text-destructive" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 添加/编辑表单 */}
      <Dialog open={showForm} onOpenChange={setShowForm}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingUser ? '编辑用户' : '添加用户'}</DialogTitle>
            <DialogDescription className="sr-only">
              {editingUser ? '编辑用户信息' : '添加新用户'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="username">用户名 *</Label>
                <Input
                  id="username"
                  value={formData.username || ''}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  placeholder="登录用户名"
                />
              </div>
              <div>
                <Label htmlFor="name">姓名 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="真实姓名"
                />
              </div>
              <div>
                <Label htmlFor="phone">电话 *</Label>
                <Input
                  id="phone"
                  value={formData.phone || ''}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  placeholder="手机号码"
                />
              </div>
              <div>
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email || ''}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  placeholder="电子邮箱"
                />
              </div>
              <div>
                <Label htmlFor="userType">用户类型 *</Label>
                <Select
                  value={formData.userType || 'enterprise_admin'}
                  onValueChange={(value: any) => {
                    setFormData({ 
                      ...formData, 
                      userType: value,
                      // 如果切换为超级管理员，清除企业信息
                      ...(value === 'super_admin' ? { enterpriseId: undefined, enterpriseName: undefined } : {})
                    });
                  }}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="super_admin">超级管理员</SelectItem>
                    <SelectItem value="enterprise_admin">企业管理员</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {formData.userType === 'enterprise_admin' && (
                <div>
                  <Label htmlFor="enterpriseId">所属企业 *</Label>
                  <Select
                    value={formData.enterpriseId || ''}
                    onValueChange={(value: string) => {
                      const selectedEnterprise = enterprises.find(e => e.id === value);
                      setFormData({ 
                        ...formData, 
                        enterpriseId: value,
                        enterpriseName: selectedEnterprise?.name
                      });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择企业" />
                    </SelectTrigger>
                    <SelectContent>
                      {enterprises.map((enterprise) => (
                        <SelectItem key={enterprise.id} value={enterprise.id}>
                          {enterprise.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowForm(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>用户详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看用户的详细信息
            </DialogDescription>
          </DialogHeader>
          {selectedUser && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>用户名</Label>
                  <div className="mt-1">{selectedUser.username}</div>
                </div>
                <div>
                  <Label>姓名</Label>
                  <div className="mt-1">{selectedUser.name}</div>
                </div>
                <div>
                  <Label>电话</Label>
                  <div className="mt-1">{selectedUser.phone}</div>
                </div>
                <div>
                  <Label>邮箱</Label>
                  <div className="mt-1">{selectedUser.email || '-'}</div>
                </div>
                <div>
                  <Label>用户类型</Label>
                  <div className="mt-1">{getUserTypeBadge(selectedUser.userType)}</div>
                </div>
                <div>
                  <Label>所属企业</Label>
                  <div className="mt-1">{selectedUser.enterpriseName || '-'}</div>
                </div>
                <div>
                  <Label>状态</Label>
                  <div className="mt-1">{getStatusBadge(selectedUser.status)}</div>
                </div>
                {selectedUser.lastLoginTime && (
                  <div>
                    <Label>最后登录</Label>
                    <div className="mt-1">
                      {new Date(selectedUser.lastLoginTime).toLocaleString('zh-CN')}
                    </div>
                  </div>
                )}
                <div>
                  <Label>创建时间</Label>
                  <div className="mt-1">
                    {new Date(selectedUser.createdAt).toLocaleString('zh-CN')}
                  </div>
                </div>
                <div>
                  <Label>更新时间</Label>
                  <div className="mt-1">
                    {new Date(selectedUser.updatedAt).toLocaleString('zh-CN')}
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
