import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Badge } from '../ui/badge';
import { UserProfile, PasswordChange } from '../../types/profile';
import { User, Mail, Phone, Building, Briefcase, Lock, Save, Shield, CheckCircle, XCircle, Clock } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { getAllEnterprises } from '../../lib/authStorage';
import type { Enterprise } from '../../types/auth';

export function PersonalInfo() {
  const [profile, setProfile] = useState<UserProfile>({
    id: 'user-1',
    username: 'admin',
    name: '系统管理员',
    email: 'admin@smart-agriculture.com',
    phone: '13800138000',
    avatar: '',
    gender: 'male',
    birthday: '1990-01-01',
    department: '技术部',
    position: '系统管理员',
    enterpriseId: 'ent-1',
    enterpriseName: '智慧农业科技有限公司',
    roleIds: ['role-1'],
    roleNames: ['超级管理员'],
    bio: '负责系统整体架构和技术管理',
    address: '北京市海淀区中关村大街1号',
    // 账户状态：'pending'待审核（企业名称可编辑）、'approved'审核通过（企业名称只读）、'rejected'驳回（企业名称只读）
    status: 'approved', // 默认审核通过
    createdAt: '2024-01-01T00:00:00',
    lastLoginTime: '2024-10-14T09:30:00',
    lastLoginIp: '192.168.1.100',
  });

  const [showPasswordDialog, setShowPasswordDialog] = useState(false);
  const [passwordForm, setPasswordForm] = useState<PasswordChange>({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  const [hasChanges, setHasChanges] = useState(false);
  
  // 获取所有企业列表
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);

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

  const loadProfile = () => {
    const data = localStorage.getItem('smart_agriculture_user_profile');
    if (data) {
      const loadedProfile = JSON.parse(data);
      // 确保所有字段都有默认值，避免undefined导致的受控组件错误
      setProfile({
        id: loadedProfile.id || 'user-1',
        username: loadedProfile.username || 'admin',
        name: loadedProfile.name || '系统管理员',
        email: loadedProfile.email || '',
        phone: loadedProfile.phone || '',
        avatar: loadedProfile.avatar || '',
        gender: loadedProfile.gender || 'male',
        birthday: loadedProfile.birthday || '',
        department: loadedProfile.department || '',
        position: loadedProfile.position || '',
        enterpriseId: loadedProfile.enterpriseId || '',
        enterpriseName: loadedProfile.enterpriseName || '',
        roleIds: loadedProfile.roleIds || ['role-1'],
        roleNames: loadedProfile.roleNames || ['超级管理员'],
        bio: loadedProfile.bio || '',
        address: loadedProfile.address || '',
        status: loadedProfile.status || 'approved',
        createdAt: loadedProfile.createdAt || new Date().toISOString(),
        lastLoginTime: loadedProfile.lastLoginTime || '',
        lastLoginIp: loadedProfile.lastLoginIp || '',
      });
    } else {
      saveProfile(profile);
    }
  };

  const loadEnterprises = () => {
    const allEnterprises = getAllEnterprises();
    // 只显示启用状态的企业
    setEnterprises(allEnterprises.filter(e => e.status === 'active'));
  };

  const saveProfile = (newProfile: UserProfile) => {
    localStorage.setItem('smart_agriculture_user_profile', JSON.stringify(newProfile));
    setProfile(newProfile);
    setHasChanges(false);
    toast.success('个人信息已保存');
  };

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

    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(profile.email)) {
      toast.error('邮箱格式不正确');
      return;
    }

    saveProfile(profile);
  };

  const handlePasswordChange = () => {
    if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      toast.error('请填写所有密码字段');
      return;
    }

    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      toast.error('两次输入的新密码不一致');
      return;
    }

    if (passwordForm.newPassword.length < 8) {
      toast.error('新密码长度不能少于8位');
      return;
    }

    // 模拟密码修改
    toast.success('密码修改成功，请重新登录');
    setShowPasswordDialog(false);
    setPasswordForm({
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    });
  };

  const updateProfile = (updates: Partial<UserProfile>) => {
    setProfile({ ...profile, ...updates });
    setHasChanges(true);
  };

  // 获取状态配置
  const getStatusConfig = (status?: string) => {
    switch (status) {
      case 'pending':
        return {
          label: '待审核',
          icon: Clock,
          className: 'bg-warning-muted text-warning-muted-foreground border-warning',
        };
      case 'approved':
        return {
          label: '审核通过',
          icon: CheckCircle,
          className: 'bg-success-muted text-success-muted-foreground border-success',
        };
      case 'rejected':
        return {
          label: '驳回',
          icon: XCircle,
          className: 'bg-error-muted text-error-muted-foreground border-error',
        };
      default:
        return {
          label: '待审核',
          icon: Clock,
          className: 'bg-muted text-muted-foreground border-border',
        };
    }
  };

  const statusConfig = getStatusConfig(profile.status);
  const StatusIcon = statusConfig.icon;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-success">个人信息</h2>
          <p className="text-muted-foreground">查看和维护个人账户信息</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => setShowPasswordDialog(true)}>
            <Lock className="w-4 h-4 mr-2" />
            修改密码
          </Button>
          <Button 
            onClick={handleSave}
            disabled={!hasChanges}
            className={hasChanges ? 'bg-success hover:bg-success/90' : ''}
          >
            <Save className="w-4 h-4 mr-2" />
            保存修改
            {hasChanges && <span className="ml-1">(有未保存更改)</span>}
          </Button>
        </div>
      </div>

      <Tabs defaultValue="basic" className="space-y-4">
        <TabsList>
          <TabsTrigger value="basic">
            <User className="w-4 h-4 mr-2" />
            基本信息
          </TabsTrigger>
          <TabsTrigger value="work">
            <Briefcase className="w-4 h-4 mr-2" />
            工作信息
          </TabsTrigger>
          <TabsTrigger value="security">
            <Shield className="w-4 h-4 mr-2" />
            安全信息
          </TabsTrigger>
        </TabsList>

        {/* 基本信息 */}
        <TabsContent value="basic" className="space-y-4">
          <Card className="p-6">
            <div className="flex items-start gap-6">
              <div className="flex flex-col items-center gap-3">
                <Avatar className="w-24 h-24">
                  <AvatarImage src={profile.avatar} />
                  <AvatarFallback className="text-2xl bg-success-muted text-success">
                    {profile.name.substring(0, 2)}
                  </AvatarFallback>
                </Avatar>
                <Button variant="outline" size="sm">
                  更换头像
                </Button>
              </div>
              <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>用户名</Label>
                  <Input
                    value={profile.username || ''}
                    disabled
                    className="bg-muted"
                  />
                </div>
                <div>
                  <Label>姓名 *</Label>
                  <Input
                    value={profile.name || ''}
                    onChange={(e) => updateProfile({ name: e.target.value })}
                    placeholder="请输入姓名"
                  />
                </div>
                <div>
                  <Label>邮箱 *</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      type="email"
                      value={profile.email || ''}
                      onChange={(e) => updateProfile({ email: e.target.value })}
                      placeholder="example@email.com"
                      className="pl-10"
                    />
                  </div>
                </div>
                <div>
                  <Label>手机号</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      value={profile.phone || ''}
                      onChange={(e) => updateProfile({ phone: e.target.value })}
                      placeholder="13800138000"
                      className="pl-10"
                    />
                  </div>
                </div>
                <div>
                  <Label>性别</Label>
                  <Select
                    value={profile.gender || 'male'}
                    onValueChange={(value: any) => updateProfile({ gender: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="male">男</SelectItem>
                      <SelectItem value="female">女</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>生日</Label>
                  <Input
                    type="date"
                    value={profile.birthday || ''}
                    onChange={(e) => updateProfile({ birthday: e.target.value })}
                  />
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 工作信息 */}
        <TabsContent value="work" className="space-y-4">
          <Card className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>企业名称</Label>
                <Select
                  value={profile.enterpriseId || ''}
                  onValueChange={(value) => {
                    const selectedEnterprise = enterprises.find(e => e.id === value);
                    if (selectedEnterprise) {
                      updateProfile({
                        enterpriseId: selectedEnterprise.id,
                        enterpriseName: selectedEnterprise.name,
                      });
                    }
                  }}
                  disabled={profile.status === 'approved'}
                >
                  <SelectTrigger className={profile.status === 'approved' ? 'bg-muted' : ''}>
                    <div className="flex items-center gap-2">
                      <Building className="w-4 h-4 text-muted-foreground" />
                      <SelectValue placeholder="请选择企业" />
                    </div>
                  </SelectTrigger>
                  <SelectContent>
                    {enterprises.length === 0 ? (
                      <div className="p-4 text-center text-sm text-muted-foreground">
                        暂无可选企业
                      </div>
                    ) : (
                      enterprises.map((enterprise) => (
                        <SelectItem key={enterprise.id} value={enterprise.id}>
                          <div className="flex items-center gap-2">
                            <span>{enterprise.name}</span>
                            <span className="text-xs text-muted-foreground">({enterprise.code})</span>
                          </div>
                        </SelectItem>
                      ))
                    )}
                  </SelectContent>
                </Select>
                {profile.status === 'pending' ? (
                  <p className="text-xs text-warning mt-1">待审核期间可修改企业信息</p>
                ) : profile.status === 'rejected' ? (
                  <p className="text-xs text-error mt-1">驳回后可修改企业信息重新提交</p>
                ) : (
                  <p className="text-xs text-muted-foreground mt-1">企业信息由管理员维护</p>
                )}
              </div>
              <div>
                <Label>部门</Label>
                <Input
                  value={profile.department || ''}
                  disabled
                  className="bg-muted"
                />
                <p className="text-xs text-muted-foreground mt-1">部门信息由管理员维护</p>
              </div>
              <div className="md:col-span-2">
                <Label>角色</Label>
                <div className="flex flex-wrap gap-2 mt-2">
                  {profile.roleNames.map((role, index) => (
                    <Badge key={index} variant="outline" className="px-3 py-1 bg-green-100 text-green-700 border-green-300 dark:bg-green-900/30 dark:text-green-400 dark:border-green-700">
                      {role}
                    </Badge>
                  ))}
                </div>
                <p className="text-xs text-muted-foreground mt-1">角色信息由管理员分配</p>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 安全信息 */}
        <TabsContent value="security" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4 text-green-800 dark:text-green-400">账户安全</h3>
            <div className="space-y-4">
              {/* 用户状态 */}
              <div className="p-4 border rounded-lg bg-card">
                <div className="flex items-center justify-between mb-3">
                  <h4>用户状态</h4>
                  <div className={`flex items-center gap-2 px-3 py-1.5 rounded-md border ${statusConfig.className}`}>
                    <StatusIcon className="w-4 h-4" />
                    <span className="text-sm font-medium">{statusConfig.label}</span>
                  </div>
                </div>
                <p className="text-sm text-muted-foreground">
                  {profile.status === 'pending' && '您的账号正在审核中，审核通过后可使用全部系统功能'}
                  {profile.status === 'approved' && '您的账号已审核通过，可以正常使用系统所有功能'}
                  {profile.status === 'rejected' && '您的账号审核未通过，请联系管理员了解详情'}
                </p>
              </div>

              {/* 登录密码 */}
              <div className="flex items-center justify-between p-4 border rounded-lg">
                <div>
                  <h4>登录密码</h4>
                  <p className="text-sm text-muted-foreground">定期修改密码可以提高账户安全性</p>
                </div>
                <Button variant="outline" onClick={() => setShowPasswordDialog(true)}>
                  修改密码
                </Button>
              </div>

              {/* 账户信息 */}
              <div className="p-4 border rounded-lg">
                <h4 className="mb-3">账户信息</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between py-1">
                    <span className="text-muted-foreground">账号创建时间</span>
                    <span className="font-medium">{new Date(profile.createdAt).toLocaleString('zh-CN')}</span>
                  </div>
                  {profile.lastLoginTime && (
                    <div className="flex justify-between py-1">
                      <span className="text-muted-foreground">最后登录时间</span>
                      <span className="font-medium">{new Date(profile.lastLoginTime).toLocaleString('zh-CN')}</span>
                    </div>
                  )}
                  {profile.lastLoginIp && (
                    <div className="flex justify-between py-1">
                      <span className="text-muted-foreground">最后登录IP</span>
                      <span>
                        <code className="text-xs bg-muted px-2 py-1 rounded font-mono">
                          {profile.lastLoginIp}
                        </code>
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 修改密码对话框 */}
      <Dialog open={showPasswordDialog} onOpenChange={setShowPasswordDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center gap-2">
                <Lock className="w-5 h-5 text-green-600" />
                修改密码
              </div>
            </DialogTitle>
            <DialogDescription className="sr-only">
              修改账户密码
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>原密码 *</Label>
              <Input
                type="password"
                value={passwordForm.oldPassword || ''}
                onChange={(e) => setPasswordForm({ ...passwordForm, oldPassword: e.target.value })}
                placeholder="请输入原密码"
              />
            </div>
            <div>
              <Label>新密码 *</Label>
              <Input
                type="password"
                value={passwordForm.newPassword || ''}
                onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
                placeholder="请输入新密码（至少8位）"
              />
            </div>
            <div>
              <Label>确认新密码 *</Label>
              <Input
                type="password"
                value={passwordForm.confirmPassword || ''}
                onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
                placeholder="请再次输入新密码"
              />
            </div>
            <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800">
              <p>密码要求：</p>
              <ul className="list-disc list-inside mt-1 space-y-1">
                <li>长度至少8位</li>
                <li>建议包含大小写字母、数字和特殊字符</li>
                <li>不要使用过于简单的密码</li>
              </ul>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPasswordDialog(false)}>
              取消
            </Button>
            <Button onClick={handlePasswordChange}>
              确认修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
        <h4 className="text-blue-900 dark:text-blue-400 mb-2">
          <User className="w-4 h-4 inline mr-2" />
          个人信息说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800 dark:text-blue-300">
          <li>• 修改个人信息后需要点击"保存修改"按钮才会生效</li>
          <li>• 待审核和驳回状态下可以从企业管理的企业列表中选择企业，审核通过后由系统管理员管理</li>
          <li>• 企业下拉列表仅显示"启用"状态的企业，数据源来自企业管理模块</li>
          <li>• 用户名、部门和角色由系统管理员管理，个人无法修改</li>
          <li>• 用户状态显示当前审核状态，影响系统功能使用权限</li>
          <li>• 定期修改密码可以提高账户安全性</li>
          <li>• 密码修改成功后需要重新登录</li>
          <li>• 所有个人信息修改都会记录到安全日志中</li>
        </ul>
      </Card>
    </div>
  );
}
