// ============================================================
// RegisterForm — 注册表单（仅个人版）
// ============================================================

import React, { useState, useCallback, useRef } from 'react';
import { Input, Button, Checkbox, Typography } from 'antd';

import { LegalTextModal } from '@/shared/components/LegalTextModal';
import {
   UserOutlined,
   LockOutlined,
   PhoneOutlined,
   SafetyCertificateOutlined,
   LaptopOutlined,
   TagOutlined,
   SmileOutlined,
   GiftOutlined,
} from '@ant-design/icons';

import { registerFields } from '../../settings/register-fields';
import { validateForm } from '../../settings/validators';
import type { RegisterFormValues } from '../../model/types';

const { Text } = Typography;

interface RegisterFormProps {
   submitting?: boolean;
   onSubmit: (values: RegisterFormValues) => void;
   onSendSms?: (phone: string) => void;
}

/** 字段名 → 图标映射 */
const iconMap: Record<string, React.ReactNode> = {
   username: <UserOutlined className="opacity-40" />,
   password: <LockOutlined className="opacity-40" />,
   confirmPassword: <LockOutlined className="opacity-40" />,
   phone: <PhoneOutlined className="opacity-40" />,
   sms_code: <SafetyCertificateOutlined className="opacity-40" />,
   device_id: <LaptopOutlined className="opacity-40" />,
   device_label: <TagOutlined className="opacity-40" />,
   display_name: <SmileOutlined className="opacity-40" />,
   referral_code: <GiftOutlined className="opacity-40" />,
};

export function RegisterForm({ submitting = false, onSubmit, onSendSms }: RegisterFormProps) {
   const [values, setValues] = useState<Record<string, string>>({});
   const [agreed, setAgreed] = useState(false);
   const [errors, setErrors] = useState<Record<string, string[]>>({});
   const [legalType, setLegalType] = useState<'service' | 'points' | null>(null);

   // 验证码冷却
   const [smsCooldown, setSmsCooldown] = useState(false);
   const [smsSeconds, setSmsSeconds] = useState(0);
   const smsTimer = useRef<ReturnType<typeof setInterval> | null>(null);

   // 字段值变更
   const handleChange = useCallback((name: string, value: string) => {
      setValues((p) => ({ ...p, [name]: value }));
      setErrors((p) => {
         const n = { ...p };
         delete n[name];
         return n;
      });
   }, []);

   // 发送验证码
   const handleSendSms = useCallback(() => {
      const phone = values.phone || '';
      const phoneConfig = registerFields.find((f) => f.name === 'phone')!;
      const phoneErrors = validateForm({ phone }, [phoneConfig]);
      if (Object.keys(phoneErrors).length > 0) {
         setErrors((p) => ({ ...p, phone: phoneErrors.phone }));
         return;
      }
      setSmsCooldown(true);
      setSmsSeconds(60);
      smsTimer.current = setInterval(() => {
         setSmsSeconds((prev) => {
            if (prev <= 1) {
               clearInterval(smsTimer.current!);
               setSmsCooldown(false);
               return 0;
            }
            return prev - 1;
         });
      }, 1000);
      onSendSms?.(phone);
   }, [values.phone, onSendSms]);

   // 提交
   const handleSubmit = useCallback(() => {
      // 跨字段校验（内联避免每次渲染创建新引用致使用 useCallback 失效）
      const crossValidators = {
         confirmPassword: (val: string) => {
            if (!val) return '请再次输入密码';
            if (val !== values.password) return '两次密码不一致';
            return null;
         },
      };
      const fieldErrors = validateForm(values, registerFields, crossValidators);
      if (Object.keys(fieldErrors).length > 0) {
         setErrors(fieldErrors);
         return;
      }
      if (!agreed) {
         setErrors({ _agreement: ['请先阅读并同意用户协议'] });
         return;
      }
      setErrors({});
      onSubmit(values as unknown as RegisterFormValues);
   }, [values, agreed, onSubmit]);

   // 渲染单个字段
   const renderField = (field: (typeof registerFields)[number]) => {
      const val = values[field.name] || '';
      const err = errors[field.name];
      const isPassword = field.inputType === 'password';
      const hasSms = field.extraAction === 'send-sms';

      return (
         <div key={field.name}>
            {hasSms ? (
               <div className="flex gap-2">
                  <Input
                     size="large"
                     prefix={iconMap[field.name]}
                     placeholder={field.placeholder}
                     value={val}
                     onChange={(e) => handleChange(field.name, e.target.value)}
                     status={err ? 'error' : undefined}
                     className="flex-1"
                     allowClear
                  />
                  <Button
                     size="large"
                     type="primary"
                     disabled={smsCooldown}
                     onClick={handleSendSms}
                     className="text-xs! shrink-0 px-3!"
                  >
                     {smsCooldown ? `${smsSeconds}s` : '发送验证码'}
                  </Button>
               </div>
            ) : isPassword ? (
               <Input.Password
                  size="large"
                  prefix={iconMap[field.name]}
                  placeholder={field.placeholder}
                  value={val}
                  onChange={(e) => handleChange(field.name, e.target.value)}
                  status={err ? 'error' : undefined}
                  allowClear
               />
            ) : (
               <Input
                  size="large"
                  prefix={iconMap[field.name]}
                  placeholder={field.placeholder}
                  value={val}
                  onChange={(e) => handleChange(field.name, e.target.value)}
                  status={err ? 'error' : undefined}
                  allowClear
               />
            )}
            {err && (
               <Text type="danger" className="text-xs ml-1">
                  {err[0]}
               </Text>
            )}
         </div>
      );
   };

   const requiredFields = registerFields.filter((f) => !f.optional);
   const optionalFields = registerFields.filter((f) => f.optional);

   return (
      <>
         <div className="space-y-4">
            {/* 必填字段 */}
            {requiredFields.map(renderField)}

            {/* 选填字段 */}
            {optionalFields.length > 0 && (
               <>
                  <Text type="secondary" className="text-xs block mt-5! mb-1!">
                     —— 以下为选填信息 ——
                  </Text>
                  {optionalFields.map(renderField)}
               </>
            )}

            {/* 邀请码说明 */}
            <Text type="secondary" className="text-xs! block mt-1!">
               填写邀请码可触发邀请佣金逻辑，审核通过后获得奖励
            </Text>

            {/* 用户协议 */}
            <div className="mt-5!">
               <Checkbox
                  checked={agreed}
                  onChange={(e) => {
                     setAgreed(e.target.checked);
                     setErrors((p) => {
                        const n = { ...p };
                        delete n._agreement;
                        return n;
                     });
                  }}
                  onKeyDown={(e)=>{
                      if(e.key==="Enter" || e.keyCode == 13) {
                          setAgreed(!agreed);
                      }
                  }}
                  className="text-xs"
               >
                  已阅读并同意
                  <a
                     className="text-xs mx-0.5"
                     onClick={(e) => {
                        e.stopPropagation();
                        setLegalType('service');
                     }}
                  >
                     《用户服务协议》
                  </a>
                  和
                  <a
                     className="text-xs mx-0.5"
                     onClick={(e) => {
                        e.stopPropagation();
                        setLegalType('points');
                     }}
                  >
                     《积分充值服务协议》
                  </a>
               </Checkbox>
               {errors._agreement && (
                  <Text type="danger" className="text-xs block mt-1">
                     {errors._agreement[0]}
                  </Text>
               )}
            </div>

            {/* 注册按钮 */}
            <Button
               type="primary"
               block
               size="large"
               loading={submitting}
               onClick={handleSubmit}
               className="h-11! text-base! font-medium! mt-2!"
            >
               注册
            </Button>
         </div>

         {/* 协议弹窗 */}
         {legalType && <LegalTextModal open type={legalType} onClose={() => setLegalType(null)} />}
      </>
   );
}
