/**
 * filekorolheader: 用户注册页面 - 新用户注册功能入口
 * 功能：用户注册、表单验证、企业选择、短信验证
 * 路径：/register
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn/ui语义化样式，支持暗色主题
 */

'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
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 { Alert, AlertDescription } from '@/components/ui/alert';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { CaptchaInput } from '@/components/auth/CaptchaInput';
import { useAuth } from '@/components/auth/AuthContext';
import { SmartFieldBackground } from '@/components/auth/SmartFieldBackground';
import { Enterprise } from '@/types/auth';
import {
  User,
  Lock,
  Phone,
  MessageSquare,
  Mail,
  UserPlus,
  Eye,
  EyeOff,
  Loader2,
  Shield,
  AlertCircle,
  CheckCircle,
  ArrowLeft,
  Building2,
} from 'lucide-react';
import { toast } from 'sonner';

export default function RegisterPage() {
  const { login } = useAuth();
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  // 导航方法封装
  const handleNavigateToLogin = () => {
    router.push('/login');
  };

  const handleNavigateToHome = () => {
    router.push('/');
  };
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [enterprises, setEnterprises] = useState<Enterprise[]>([]);

  const [form, setForm] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    code: '',
    realName: '',
    email: '',
    enterpriseId: '',
    captcha: '',
  });

  const [validation, setValidation] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    realName: '',
  });

  // 加载企业列表
  useEffect(() => {
    const mockEnterprises: Enterprise[] = [
      {
        id: '1',
        name: '智慧农业示范农场',
        code: 'DEMO001',
        type: '示范农场',
        status: 'active',
        createdAt: new Date().toISOString(),
      },
      {
        id: '2',
        name: '绿色生态农业基地',
        code: 'ECO002',
        type: '生态农场',
        status: 'active',
        createdAt: new Date().toISOString(),
      },
      {
        id: '3',
        name: '科技农业产业园',
        code: 'TECH003',
        type: '产业园区',
        status: 'active',
        createdAt: new Date().toISOString(),
      },
    ];
    setEnterprises(mockEnterprises);
  }, []);

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  // 验证函数
  const validateUsername = (username: string): string => {
    if (!username) return '请输入用户名';
    if (username.length < 3) return '用户名至少3个字符';
    if (username.length > 20) return '用户名最多20个字符';
    if (!/^[a-zA-Z0-9_]+$/.test(username)) return '用户名只能包含字母、数字和下划线';
    return '';
  };

  const validatePassword = (password: string): string => {
    if (!password) return '请输入密码';
    if (password.length < 6) return '密码至少6个字符';
    if (password.length > 20) return '密码最多20个字符';
    return '';
  };

  const validateConfirmPassword = (confirmPassword: string, password: string): string => {
    if (!confirmPassword) return '请确认密码';
    if (confirmPassword !== password) return '两次密码输入不一致';
    return '';
  };

  const validatePhone = (phone: string): string => {
    if (!phone) return '请输入手机号';
    if (!/^1[3-9]\d{9}$/.test(phone)) return '请输入正确的手机号';
    return '';
  };

  const validateRealName = (realName: string): string => {
    if (!realName) return '请输入真实姓名';
    if (realName.length < 2) return '姓名至少2个字符';
    if (realName.length > 20) return '姓名最多20个字符';
    return '';
  };

  // 发送验证码
  const handleSendCode = async () => {
    const phoneError = validatePhone(form.phone);

    if (phoneError) {
      setValidation(prev => ({ ...prev, phone: phoneError }));
      toast.error(phoneError);
      return;
    }

    setSendingCode(true);
    setError('');

    try {
      // 模拟发送验证码
      await new Promise(resolve => setTimeout(resolve, 1000));
      toast.success('验证码发送成功！（测试验证码：123456）');
      setCountdown(60);
    } catch (err) {
      setError('发送验证码失败，请稍后重试');
      toast.error('发送验证码失败');
    } finally {
      setSendingCode(false);
    }
  };

  // 注册处理
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    // 验证所有字段
    const usernameError = validateUsername(form.username);
    const passwordError = validatePassword(form.password);
    const confirmPasswordError = validateConfirmPassword(form.confirmPassword, form.password);
    const phoneError = validatePhone(form.phone);
    const realNameError = validateRealName(form.realName);

    setValidation({
      username: usernameError,
      password: passwordError,
      confirmPassword: confirmPasswordError,
      phone: phoneError,
      realName: realNameError,
    });

    if (usernameError || passwordError || confirmPasswordError || phoneError || realNameError) {
      setError('请检查表单填写是否正确');
      return;
    }

    if (!form.code) {
      setError('请输入短信验证码');
      return;
    }

    if (!form.captcha) {
      setError('请输入图形验证码');
      return;
    }

    setLoading(true);

    try {
      // 模拟注册
      await new Promise(resolve => setTimeout(resolve, 1500));

      if (form.code === '123456') {
        setSuccess('注册成功！正在为您自动登录...');
        toast.success('注册成功！');

        // 自动登录
        setTimeout(() => {
          login({
            id: '3',
            username: form.username,
            realName: form.realName,
            email: form.email,
            phone: form.phone,
            role: 'user',
            permissions: [],
            enterpriseId: form.enterpriseId,
            enterpriseName: enterprises.find(e => e.id === form.enterpriseId)?.name || '',
            createdAt: new Date().toISOString(),
          });
          handleNavigateToHome();
        }, 1500);
      } else {
        setError('短信验证码错误');
        toast.error('短信验证码错误');
      }
    } catch (err) {
      setError('注册失败，请稍后重试');
      toast.error('注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4 relative overflow-hidden">
      {/* 智慧大田动态背景 */}
      <SmartFieldBackground />

      {/* 内容区域 */}
      <div className="w-full max-w-md relative z-10">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-white/90 backdrop-blur-sm rounded-2xl mb-4 shadow-lg">
            <Shield className="w-8 h-8 text-green-600" />
          </div>
          <h1 className="text-white mb-2 drop-shadow-lg">智慧农业生产管理系统</h1>
          <p className="text-sm text-white/90 drop-shadow-md">安全、智能、高效的农业管理平台</p>
        </div>

        <Card className="p-8 shadow-2xl bg-white/95 backdrop-blur-md border-white/20">
          {/* 返回登录 */}
          <div className="mb-6">
            <button
              type="button"
              onClick={handleNavigateToLogin}
              className="flex items-center text-sm text-muted-foreground hover:text-foreground"
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回登录
            </button>
          </div>

          {error && (
            <Alert className="mb-4 bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800">
              <AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400" />
              <AlertDescription className="text-red-700 dark:text-red-300">{error}</AlertDescription>
            </Alert>
          )}

          {success && (
            <Alert className="mb-4 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
              <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400" />
              <AlertDescription className="text-green-700 dark:text-green-300">{success}</AlertDescription>
            </Alert>
          )}

          <form onSubmit={handleRegister} className="space-y-4">
            {/* 用户名 */}
            <div>
              <Label>用户名</Label>
              <div className="relative mt-2">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type="text"
                  placeholder="请输入用户名（字母、数字、下划线）"
                  value={form.username}
                  onChange={(e) => {
                    setForm({ ...form, username: e.target.value });
                    setValidation({ ...validation, username: '' });
                  }}
                  onBlur={(e) => setValidation({ ...validation, username: validateUsername(e.target.value) })}
                  className="pl-10"
                  disabled={loading}
                />
              </div>
              {validation.username && (
                <p className="text-xs text-red-600 mt-1">{validation.username}</p>
              )}
            </div>

            {/* 真实姓名 */}
            <div>
              <Label>真实姓名</Label>
              <div className="relative mt-2">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type="text"
                  placeholder="请输入真实姓名"
                  value={form.realName}
                  onChange={(e) => {
                    setForm({ ...form, realName: e.target.value });
                    setValidation({ ...validation, realName: '' });
                  }}
                  onBlur={(e) => setValidation({ ...validation, realName: validateRealName(e.target.value) })}
                  className="pl-10"
                  disabled={loading}
                />
              </div>
              {validation.realName && (
                <p className="text-xs text-red-600 mt-1">{validation.realName}</p>
              )}
            </div>

            {/* 手机号 */}
            <div>
              <Label>手机号</Label>
              <div className="relative mt-2">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type="tel"
                  placeholder="请输入手机号"
                  value={form.phone}
                  onChange={(e) => {
                    setForm({ ...form, phone: e.target.value });
                    setValidation({ ...validation, phone: '' });
                  }}
                  onBlur={(e) => setValidation({ ...validation, phone: validatePhone(e.target.value) })}
                  className="pl-10"
                  maxLength={11}
                  disabled={loading}
                />
              </div>
              {validation.phone && (
                <p className="text-xs text-red-600 mt-1">{validation.phone}</p>
              )}
            </div>

            {/* 短信验证码 */}
            <div>
              <Label>短信验证码</Label>
              <div className="flex gap-2 mt-2">
                <div className="relative flex-1">
                  <MessageSquare className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    type="text"
                    placeholder="请输入验证码"
                    value={form.code}
                    onChange={(e) => setForm({ ...form, code: e.target.value })}
                    className="pl-10"
                    maxLength={6}
                    disabled={loading}
                  />
                </div>
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleSendCode}
                  disabled={sendingCode || countdown > 0 || loading}
                  className="min-w-[120px]"
                >
                  {sendingCode ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : countdown > 0 ? (
                    `${countdown}秒后重试`
                  ) : (
                    '发送验证码'
                  )}
                </Button>
              </div>
            </div>

            {/* 所属企业 */}
            <div>
              <Label>所属企业</Label>
              <Select
                value={form.enterpriseId}
                onValueChange={(value) => setForm({ ...form, enterpriseId: value })}
                disabled={loading}
              >
                <SelectTrigger className="mt-2">
                  <div className="flex items-center gap-2">
                    <Building2 className="w-4 h-4 text-muted-foreground" />
                    <SelectValue placeholder="请选择所属企业" />
                  </div>
                </SelectTrigger>
                <SelectContent>
                  {enterprises.map((enterprise) => (
                    <SelectItem key={enterprise.id} value={enterprise.id}>
                      <div className="flex flex-col">
                        <span>{enterprise.name}</span>
                        <span className="text-xs text-muted-foreground">
                          {enterprise.code} · {enterprise.type}
                        </span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 邮箱（可选） */}
            <div>
              <Label>邮箱（可选）</Label>
              <div className="relative mt-2">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type="email"
                  placeholder="请输入邮箱"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  className="pl-10"
                  disabled={loading}
                />
              </div>
            </div>

            {/* 密码 */}
            <div>
              <Label>密码</Label>
              <div className="relative mt-2">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type={showPassword ? 'text' : 'password'}
                  placeholder="请输入密码（至少6位）"
                  value={form.password}
                  onChange={(e) => {
                    setForm({ ...form, password: e.target.value });
                    setValidation({ ...validation, password: '' });
                  }}
                  onBlur={(e) => setValidation({ ...validation, password: validatePassword(e.target.value) })}
                  className="pl-10 pr-10"
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              {validation.password && (
                <p className="text-xs text-red-600 mt-1">{validation.password}</p>
              )}
            </div>

            {/* 确认密码 */}
            <div>
              <Label>确认密码</Label>
              <div className="relative mt-2">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <Input
                  type={showConfirmPassword ? 'text' : 'password'}
                  placeholder="请再次输入密码"
                  value={form.confirmPassword}
                  onChange={(e) => {
                    setForm({ ...form, confirmPassword: e.target.value });
                    setValidation({ ...validation, confirmPassword: '' });
                  }}
                  onBlur={(e) => setValidation({ ...validation, confirmPassword: validateConfirmPassword(e.target.value, form.password) })}
                  className="pl-10 pr-10"
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              {validation.confirmPassword && (
                <p className="text-xs text-red-600 mt-1">{validation.confirmPassword}</p>
              )}
            </div>

            {/* 图形验证码 */}
            <div>
              <Label>图形验证码</Label>
              <CaptchaInput
                value={form.captcha}
                onChange={(value) => setForm({ ...form, captcha: value })}
                className="mt-2"
              />
            </div>

            {/* 注册按钮 */}
            <Button type="submit" className="w-full bg-green-600 hover:bg-green-700" disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  注册中...
                </>
              ) : (
                <>
                  <UserPlus className="w-4 h-4 mr-2" />
                  立即注册
                </>
              )}
            </Button>
          </form>

          {/* 提示信息 */}
          <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div className="flex items-start gap-2">
              <Shield className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
              <div className="text-xs text-blue-900 dark:text-blue-100">
                <p className="mb-1">注册说明：</p>
                <ul className="space-y-0.5">
                  <li>• 请先选择所属企业或农场</li>
                  <li>• 用户名和手机号必须唯一</li>
                  <li>• 密码至少6位，建议包含字母和数字</li>
                  <li>• 测试验证码：123456</li>
                  <li>• 注册成功后自动登录系统</li>
                </ul>
              </div>
            </div>
          </div>
        </Card>

        {/* 页脚 */}
        <div className="mt-6 text-center text-xs text-white/80 drop-shadow-md">
          <p>© 2024 智慧农业生产管理系统. All rights reserved.</p>
        </div>
      </div>
    </div>
  );
}