'use client';

import { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { UserProfile, PasswordChange } from '@/types/profile';
import { User, Mail, Phone, Building, Briefcase, Lock, Save, Shield } from 'lucide-react';
import { toast } from 'sonner';
import { useAuth } from '@/components/auth/AuthContext';

export default function PersonalInfo() {
  const { user } = useAuth();

  const [profile, setProfile] = useState<UserProfile>({
    id: user?.id || '',
    username: user?.username || '',
    name: user?.realName || '',
    email: user?.email || '',
    phone: user?.phone || '',
    avatar: '',
    gender: '',
    birthday: '',
    department: '',
    position: '',
    enterpriseId: user?.enterpriseId || '',
    enterpriseName: user?.enterpriseName || '',
    roleIds: [],
    roleNames: user?.is_superuser ? ['超级管理员'] : ['普通用户'],
    bio: '',
    address: '',
    createdAt: user?.createdAt || '',
    lastLoginTime: '',
    lastLoginIp: '',
  });

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

  const [hasChanges, setHasChanges] = useState(false);

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

  // 当用户信息变化时，更新 profile 状态
  useEffect(() => {
    if (user) {
      setProfile(prev => ({
        ...prev,
        id: user.id || '',
        username: user.username || '',
        name: user.realName || '',
        email: user.email || '',
        phone: user.phone || '',
        enterpriseId: user.enterpriseId || '',
        enterpriseName: user.enterpriseName || '',
        roleNames: user.is_superuser ? ['超级管理员'] : ['普通用户'],
        createdAt: user.createdAt || '',
      }));
    }
  }, [user]);

  const loadProfile = () => {
    const data = localStorage.getItem('smart_agriculture_user_profile');
    if (data) {
      setProfile(JSON.parse(data));
    } else {
      saveProfile(profile);
    }
  };

  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);
  };

  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={() => setShowPasswordDialog(true)}>
            <Lock className="w-4 h-4 mr-2" />
            修改密码
          </Button>
          <Button
            onClick={handleSave}
            disabled={!hasChanges}
            className={hasChanges ? 'bg-green-600 hover:bg-green-700' : ''}
          >
            <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-green-100 text-green-700">
                    {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-gray-50"
                  />
                </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}
                    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 className="md:col-span-2">
                  <Label>个人简介</Label>
                  <Textarea
                    value={profile.bio}
                    onChange={(e) => updateProfile({ bio: e.target.value })}
                    placeholder="介绍一下自己"
                    rows={3}
                  />
                </div>
                <div className="md:col-span-2">
                  <Label>地址</Label>
                  <Input
                    value={profile.address}
                    onChange={(e) => updateProfile({ address: e.target.value })}
                    placeholder="请输入地址"
                  />
                </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>
                <div className="relative">
                  <Building className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    value={profile.enterpriseName}
                    disabled
                    className="pl-10 bg-gray-50"
                  />
                </div>
              </div>
              <div>
                <Label>部门</Label>
                <Input
                  value={profile.department}
                  onChange={(e) => updateProfile({ department: e.target.value })}
                  placeholder="请输入部门"
                />
              </div>
              <div>
                <Label>职位</Label>
                <Input
                  value={profile.position}
                  onChange={(e) => updateProfile({ position: e.target.value })}
                  placeholder="请输入职位"
                />
              </div>
              <div>
                <Label>角色</Label>
                <div className="flex flex-wrap gap-2 pt-2">
                  {profile.roleNames.map((role, index) => (
                    <div key={index} className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm">
                      {role}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 安全信息 */}
        <TabsContent value="security" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">账户安全</h3>
            <div className="space-y-4">
              <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-2">账户信息</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">账号创建时间</span>
                    <span>{new Date(profile.createdAt).toLocaleString('zh-CN')}</span>
                  </div>
                  {profile.lastLoginTime && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">最后登录时间</span>
                      <span>{new Date(profile.lastLoginTime).toLocaleString('zh-CN')}</span>
                    </div>
                  )}
                  {profile.lastLoginIp && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">最后登录IP</span>
                      <span>
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {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 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <User className="w-4 h-4 inline mr-2" />
          个人信息说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 修改个人信息后需要点击"保存修改"按钮才会生效</li>
          <li>• 用户名和企业信息由系统管理员管理，个人无法修改</li>
          <li>• 定期修改密码可以提高账户安全性</li>
          <li>• 密码修改成功后需要重新登录</li>
          <li>• 所有个人信息修改都会记录到安全日志中</li>
        </ul>
      </Card>
    </div>
  );
}