import React, { useMemo } from 'react';
import type { CustomerCreateForm } from '../types';
import {
  COOP_STATUS_OPTIONS,
  CUSTOMER_TYPE_OPTIONS,
  DEPT_MANAGER_MAP,
  REGION_TREE,
} from '../utils/constants';
import { parseAddressToRegion, formatProvinceCity } from '../utils/address';

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

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

export function CreatePage({
  form,
  onChange,
  onReset,
  onSubmit,
  onBack,
}: CreatePageProps) {
  const cityOptions = useMemo(() => {
    const node = REGION_TREE.find((item) => item.province === form.cityProvince);
    return node?.cities ?? [];
  }, [form.cityProvince]);

  const managerOptions = form.department ? (DEPT_MANAGER_MAP[form.department] ?? []) : [];

  const handleNameChange = (customerName: string) => {
    onChange({ customerName, invoiceTitle: customerName });
  };

  const handleDepartmentChange = (department: string) => {
    onChange({ department, manager: '' });
  };

  const handleAddressChange = (address: string) => {
    const { cityProvince, cityName } = parseAddressToRegion(address);
    onChange({ address, cityProvince, cityName });
  };

  const provinceCityDisplay = formatProvinceCity(form.cityProvince, form.cityName);

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

      <section className="cm-form-card" data-annotation-id="cm-create-base">
        <h2 className="cm-form-card-title">客户信息</h2>
        <div className="cm-form-grid">
          <FormField label="客户类型" required>
            <select
              className="vm-input"
              value={form.customerType}
              onChange={(event) => onChange({ customerType: event.target.value })}
            >
              {CUSTOMER_TYPE_OPTIONS.map((option) => (
                <option key={option} value={option}>{option}</option>
              ))}
            </select>
          </FormField>
          <FormField label="客户全称" required>
            <input
              className="vm-input"
              value={form.customerName}
              placeholder="与客户证照一致"
              onChange={(event) => handleNameChange(event.target.value)}
            />
          </FormField>
          <FormField label="客户简称">
            <input
              className="vm-input"
              value={form.customerShortName}
              placeholder="选填"
              onChange={(event) => onChange({ customerShortName: event.target.value })}
            />
          </FormField>
          <FormField label="省市" hint="自动从地址解析">
            <input
              className="vm-input cm-input-disabled"
              value={provinceCityDisplay}
              placeholder="自动从地址解析"
              disabled
              readOnly
            />
          </FormField>
          <FormField label="所属城市" required hint="自动从通讯地址识别，不可手选">
            <div className="cm-city-row">
              <select
                className="vm-input cm-input-disabled"
                value={form.cityProvince}
                disabled
              >
                <option value="">请选择省份</option>
                {REGION_TREE.map((item) => (
                  <option key={item.province} value={item.province}>{item.province}</option>
                ))}
              </select>
              <select
                className="vm-input cm-input-disabled"
                value={form.cityName}
                disabled
              >
                <option value="">请选择城市</option>
                {cityOptions.map((city) => (
                  <option key={city} value={city}>{city}</option>
                ))}
              </select>
            </div>
          </FormField>
          <FormField label="通讯地址" required hint="填写完整地址自动识别省市">
            <input
              className="vm-input"
              value={form.address}
              placeholder="填写完整地址自动解析省市和详细地址"
              onChange={(event) => handleAddressChange(event.target.value)}
            />
          </FormField>
          <FormField label="业务负责部门" required>
            <select
              className="vm-input"
              value={form.department}
              onChange={(event) => handleDepartmentChange(event.target.value)}
            >
              <option value="">请选择业务负责部门</option>
              {Object.keys(DEPT_MANAGER_MAP).map((dept) => (
                <option key={dept} value={dept}>{dept}</option>
              ))}
            </select>
          </FormField>
          <FormField label="业务负责人员" required>
            <select
              className="vm-input"
              value={form.manager}
              disabled={!form.department}
              onChange={(event) => onChange({ manager: event.target.value })}
            >
              <option value="">请选择业务负责人员</option>
              {managerOptions.map((manager) => (
                <option key={manager} value={manager}>{manager}</option>
              ))}
            </select>
          </FormField>
          <FormField label="合作状态">
            <select
              className={`vm-input ${!form.coopStatus ? 'cm-select-placeholder' : ''}`}
              value={form.coopStatus}
              onChange={(event) => onChange({ coopStatus: event.target.value })}
            >
              <option value="">请选择合作状态</option>
              {COOP_STATUS_OPTIONS.map((option) => (
                <option key={option} value={option}>{option}</option>
              ))}
            </select>
          </FormField>
          <FormField label="备注" hint="">
            <textarea
              className="vm-input cm-textarea"
              rows={3}
              value={form.remark}
              placeholder="请输入备注"
              onChange={(event) => onChange({ remark: event.target.value })}
            />
          </FormField>
        </div>
      </section>

      <section className="cm-form-card" data-annotation-id="cm-create-contact">
        <h2 className="cm-form-card-title">联系人信息</h2>
        <div className="cm-form-grid">
          <FormField label="姓名">
            <input
              className="vm-input"
              value={form.contactName}
              placeholder="请输入姓名"
              onChange={(event) => onChange({ contactName: event.target.value })}
            />
          </FormField>
          <FormField label="手机号">
            <input
              className="vm-input"
              value={form.contactPhone}
              placeholder="请输入手机号"
              onChange={(event) => onChange({ contactPhone: event.target.value })}
            />
          </FormField>
          <FormField label="职位">
            <input
              className="vm-input"
              value={form.contactPosition}
              placeholder="请输入职位"
              onChange={(event) => onChange({ contactPosition: event.target.value })}
            />
          </FormField>
        </div>
      </section>

      <section className="cm-form-card" data-annotation-id="cm-create-invoice">
        <h2 className="cm-form-card-title">付款及开票信息</h2>
        <div className="cm-form-grid">
          <FormField label="发票抬头" required hint="自动带入客户全称">
            <input
              className="vm-input cm-input-disabled"
              value={form.invoiceTitle}
              placeholder="自动带入客户全称"
              disabled
              readOnly
            />
          </FormField>
          <FormField label="纳税人识别号" required>
            <input
              className="vm-input"
              value={form.taxId}
              placeholder="请输入纳税人识别号"
              onChange={(event) => onChange({ taxId: event.target.value })}
            />
          </FormField>
          <FormField label="注册地址">
            <input
              className="vm-input"
              value={form.regAddress}
              placeholder="请输入注册地址"
              onChange={(event) => onChange({ regAddress: event.target.value })}
            />
          </FormField>
          <FormField label="注册电话">
            <input
              className="vm-input"
              value={form.regPhone}
              placeholder="请输入注册电话"
              onChange={(event) => onChange({ regPhone: event.target.value })}
            />
          </FormField>
          <FormField label="开户银行" required>
            <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>

      <footer className="cm-create-footer" data-annotation-id="cm-create-footer">
        <button type="button" className="vm-btn vm-btn-ghost ldb-toolbar-btn" onClick={onReset} data-vm-icon="rotate-ccw">重置</button>
        <button type="button" className="vm-btn vm-btn-primary" onClick={onSubmit} data-vm-icon="send">提交</button>
      </footer>
    </div>
  );
}
