import React, { useRef } from 'react';
import { Upload } from 'lucide-react';
import type { SupplierCreateForm } from '../types';
import { CONTRACTING_COMPANY_OPTIONS } from '../utils/constants';
import { resolveAddressFromDetail } from '../utils/address';

interface CreatePageProps {
  form: SupplierCreateForm;
  onChange: (patch: Partial<SupplierCreateForm>) => void;
  onSave: () => void;
  onSubmit: () => void;
  onBack: () => void;
}

function FormField({
  label,
  required,
  hint,
  fullWidth,
  children,
}: {
  label: string;
  required?: boolean;
  hint?: string;
  fullWidth?: boolean;
  children: React.ReactNode;
}) {
  return (
    <label className={`sm-form-field ${fullWidth ? 'sm-form-field-full' : ''}`}>
      <span className="sm-form-label">
        {label}
        {required && <span className="sm-required" aria-hidden>*</span>}
      </span>
      {children}
      {hint && <span className="sm-form-hint">{hint}</span>}
    </label>
  );
}

function UploadField({
  label,
  hint,
  accept,
  multiple,
  fileNames,
  onUpload,
}: {
  label: string;
  hint: string;
  accept: string;
  multiple?: boolean;
  fileNames: string[];
  onUpload: (files: FileList | null) => void;
}) {
  const inputRef = useRef<HTMLInputElement>(null);

  return (
    <div className="sm-upload-field">
      <span className="sm-form-label">{label}</span>
      <button
        type="button"
        className="vm-upload-zone sm-upload-zone"
        onClick={() => inputRef.current?.click()}
      >
        <Upload size={28} aria-hidden />
        <p>点击或拖拽上传</p>
        <p className="hint">{hint}</p>
        <input
          ref={inputRef}
          type="file"
          accept={accept}
          multiple={multiple}
          className="sr-only"
          onChange={(event) => onUpload(event.target.files)}
        />
      </button>
      {fileNames.length > 0 && (
        <ul className="sm-upload-files">
          {fileNames.map((name) => (
            <li key={name}>{name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export function CreatePage({
  form,
  onChange,
  onSave,
  onSubmit,
  onBack,
}: CreatePageProps) {
  const handleDetailAddressChange = (value: string) => {
    const resolved = resolveAddressFromDetail(value);
    onChange({
      detailAddress: value,
      region: resolved.region,
      provinceCity: resolved.provinceCity,
      cityDisplay: resolved.cityDisplay,
    });
  };

  const handleBusinessLicenseUpload = (files: FileList | null) => {
    const file = files?.[0];
    if (!file) return;
    onChange({
      businessLicenseFile: file.name,
      supplierName: form.supplierName || '嘉兴某某科技有限公司',
      taxId: form.taxId || '91330400MA2XXXXX1',
      regAddress: form.regAddress || '浙江省嘉兴市南湖区科技大道1号',
    });
  };

  const handleOtherDocsUpload = (files: FileList | null) => {
    if (!files?.length) return;
    const names = Array.from(files).map((file) => file.name);
    onChange({ otherDocFiles: [...form.otherDocFiles, ...names] });
  };

  return (
    <div className="sm-create-page">
      <div className="vm-form-topbar">
        <button type="button" className="vm-btn vm-btn-back" onClick={onBack}>返回</button>
      </div>

      <section className="sm-form-card" data-annotation-id="sm-create-entity">
        <h2 className="sm-form-card-title">地址信息</h2>
        <p className="sm-section-hint">填写详细地址后自动解析所属区域与城市（直辖市显示为「xx市xx区」）</p>
        <div className="sm-form-grid">
          <FormField label="签约公司" required>
            <select
              className={`vm-input ${!form.contractingCompany ? 'sm-select-placeholder' : ''}`}
              value={form.contractingCompany}
              onChange={(event) => onChange({ contractingCompany: event.target.value })}
            >
              <option value="" disabled>请选择羚牛签约主体</option>
              {CONTRACTING_COMPANY_OPTIONS.map((option) => (
                <option key={option} value={option}>{option}</option>
              ))}
            </select>
          </FormField>
          <FormField label="供应商名称" required>
            <input
              className="vm-input"
              value={form.supplierName}
              placeholder="请输入供应商名称"
              onChange={(event) => onChange({ supplierName: event.target.value })}
            />
          </FormField>
          <FormField label="区域">
            <input
              className="vm-input sm-input-disabled"
              value={form.region}
              placeholder="自动从详细地址解析"
              readOnly
              aria-readonly
            />
          </FormField>
          <FormField label="城市">
            <input
              className="vm-input sm-input-disabled"
              value={form.cityDisplay}
              placeholder="自动从详细地址解析"
              readOnly
              aria-readonly
            />
          </FormField>
          <FormField label="详细地址" fullWidth>
            <input
              className="vm-input"
              value={form.detailAddress}
              placeholder="请输入完整地址，如：浙江省嘉兴市南湖区科技大道1号"
              onChange={(event) => handleDetailAddressChange(event.target.value)}
            />
          </FormField>
        </div>
      </section>

      <section className="sm-form-card" data-annotation-id="sm-create-contact">
        <h2 className="sm-form-card-title">联系人信息</h2>
        <div className="sm-form-grid">
          <FormField label="联系人姓名" required>
            <input
              className="vm-input"
              value={form.contact}
              placeholder="请输入联系人"
              onChange={(event) => onChange({ contact: event.target.value })}
            />
          </FormField>
          <FormField label="联系人手机" hint="手机与座机至少填一项">
            <input
              className="vm-input"
              value={form.contactMobile}
              placeholder="11位手机号"
              onChange={(event) => onChange({ contactMobile: event.target.value })}
            />
          </FormField>
          <FormField label="联系人座机">
            <input
              className="vm-input"
              value={form.contactPhone}
              placeholder="手机号或固定电话"
              onChange={(event) => onChange({ contactPhone: event.target.value })}
            />
          </FormField>
        </div>
      </section>

      <section className="sm-form-card" data-annotation-id="sm-create-invoice">
        <h2 className="sm-form-card-title">开票信息</h2>
        <div className="sm-form-grid">
          <FormField label="纳税人识别号">
            <input
              className="vm-input"
              value={form.taxId}
              placeholder="请输入纳税人识别号"
              onChange={(event) => onChange({ taxId: event.target.value })}
            />
          </FormField>
          <FormField label="注册电话">
            <input
              className="vm-input"
              value={form.regPhone}
              placeholder="手机号或固定电话"
              onChange={(event) => onChange({ regPhone: event.target.value })}
            />
          </FormField>
          <FormField label="注册地址">
            <input
              className="vm-input"
              value={form.regAddress}
              placeholder="请输入注册地址"
              onChange={(event) => onChange({ regAddress: event.target.value })}
            />
          </FormField>
        </div>
      </section>

      <section className="sm-form-card" data-annotation-id="sm-create-bank">
        <h2 className="sm-form-card-title">银行账户</h2>
        <div className="sm-form-grid sm-form-grid-2">
          <FormField label="开户行">
            <input
              className="vm-input"
              value={form.bankName}
              placeholder="请输入开户行"
              onChange={(event) => onChange({ bankName: event.target.value })}
            />
          </FormField>
          <FormField label="银行账号">
            <input
              className="vm-input"
              value={form.bankAccount}
              placeholder="请输入银行账号"
              onChange={(event) => onChange({ bankAccount: event.target.value })}
            />
          </FormField>
        </div>
      </section>

      <section className="sm-form-card" data-annotation-id="sm-create-docs">
        <h2 className="sm-form-card-title">资质证照</h2>
        <div className="sm-upload-grid">
          <UploadField
            label="营业执照"
            hint="支持 OCR 识别，上传后自动反写名称、税号、通讯地址"
            accept=".pdf,.jpg,.jpeg,.png"
            fileNames={form.businessLicenseFile ? [form.businessLicenseFile] : []}
            onUpload={handleBusinessLicenseUpload}
          />
          <UploadField
            label="其他证件"
            hint="支持多文件上传，不限数量，PDF、图片"
            accept=".pdf,.jpg,.jpeg,.png"
            multiple
            fileNames={form.otherDocFiles}
            onUpload={handleOtherDocsUpload}
          />
        </div>
      </section>

      <footer className="sm-create-footer" data-annotation-id="sm-create-footer">
        <button type="button" className="vm-btn vm-btn-ghost" onClick={onBack} data-vm-icon="x">返回</button>
        <div className="sm-create-footer-actions">
          <button type="button" className="vm-btn vm-btn-secondary" onClick={onSave} data-vm-icon="save">保存</button>
          <button type="button" className="vm-btn vm-btn-primary" onClick={onSubmit} data-vm-icon="send">提交</button>
        </div>
      </footer>
    </div>
  );
}
