// ============================================================
// FormField — 通用表单字段渲染器（数据驱动）
//
// 根据 FieldConfig 自动选择 Input / Input.Password / 带短信按钮的复合控件。
// 原在 src/pages/auth/components/FormField.tsx，
// 提升到 src/components/ui/ 供跨页面复用。
// ============================================================

import { useCallback } from 'react';
import { Input, Button, Form } from 'antd';
import type { FieldConfig } from './types';

interface FormFieldProps {
   config: FieldConfig;
   value: string;
   onChange: (name: string, value: string) => void;
   errors: string[];
   onSendSms?: () => void;
   smsCooldown?: boolean;
   smsSecondsLeft?: number;
}

export function FormField({
   config,
   value,
   onChange,
   errors,
   onSendSms,
   smsCooldown,
   smsSecondsLeft,
}: FormFieldProps) {
   const hasError = errors.length > 0;
   const isPassword = config.inputType === 'password';

   const handleChange = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>) => {
         onChange(config.name, e.target.value);
      },
      [config.name, onChange],
   );

   return (
      <Form.Item
         label={
            <span className="text-xs">
               {config.label}
               {config.optional && <span className="text-gray-400 ml-1">(选填)</span>}
            </span>
         }
         validateStatus={hasError ? 'error' : undefined}
         help={hasError ? errors[0] : undefined}
         className="!mb-3"
      >
         {isPassword ? (
            <Input.Password
               value={value}
               onChange={handleChange}
               placeholder={config.placeholder}
               size="middle"
               allowClear
            />
         ) : config.extraAction === 'send-sms' ? (
            <div className="flex gap-2">
               <Input
                  value={value}
                  onChange={handleChange}
                  placeholder={config.placeholder}
                  size="middle"
                  className="flex-1"
                  allowClear
               />
               <Button
                  size="middle"
                  disabled={smsCooldown}
                  onClick={onSendSms}
                  className="shrink-0 text-xs"
               >
                  {smsCooldown ? `${smsSecondsLeft}s` : '发送验证码'}
               </Button>
            </div>
         ) : (
            <Input
               value={value}
               onChange={handleChange}
               placeholder={config.placeholder}
               size="middle"
               allowClear
            />
         )}
      </Form.Item>
   );
}
