import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import { request } from '../lib/api';
import {
  clearStoreDraft,
  defaultStoreForm,
  loadStoreDraft,
  saveStoreDraft,
  type StoreDraftForm,
  validateStoreStep1,
  validateStoreStep3,
} from '../lib/storeDraft';

const STEPS = ['基本信息', '照片上传', '结算资质'] as const;

export default function StoreCreatePage() {
  const navigate = useNavigate();
  const [params, setParams] = useSearchParams();
  const saved = loadStoreDraft();
  const [form, setForm] = useState<StoreDraftForm>(saved?.form ?? defaultStoreForm());
  const [error, setError] = useState('');

  const stepFromUrl = Number(params.get('step') || 0);
  const step = stepFromUrl >= 1 && stepFromUrl <= 3 ? stepFromUrl : (saved?.step ?? 1);

  useEffect(() => {
    if (!stepFromUrl && saved?.step) {
      setParams({ step: String(saved.step) }, { replace: true });
    }
  }, [stepFromUrl, saved?.step, setParams]);

  useEffect(() => {
    saveStoreDraft({ step, form });
  }, [step, form]);

  function patchForm(patch: Partial<StoreDraftForm>) {
    setForm((prev) => ({ ...prev, ...patch }));
    setError('');
  }

  function goStep(n: number) {
    setParams({ step: String(n) });
    setError('');
  }

  function handleNext() {
    if (step === 1) {
      const msg = validateStoreStep1(form);
      if (msg) { setError(msg); return; }
    }
    goStep(step + 1);
  }

  async function submit() {
    const msg = validateStoreStep3(form);
    if (msg) { setError(msg); return; }
    const step1Msg = validateStoreStep1(form);
    if (step1Msg) { setError(step1Msg); return; }

    await request('PARTNER_H5', '/partner/stores', {
      method: 'POST',
      body: JSON.stringify({
        name: form.name.trim(),
        phone: form.phone.trim(),
        district: form.district.trim(),
        address: form.address.trim(),
        intro: form.intro.trim() || undefined,
        bankAccountName: form.bankAccountName.trim(),
        bankAccountNo: form.bankAccountNo.replace(/\s/g, ''),
        bankBranch: form.bankBranch.trim(),
      }),
    });
    clearStoreDraft();
    navigate('/stores');
  }

  const progress = step === 1 ? 0 : step === 2 ? 50 : 100;

  return (
    <div className="partner-page-sticky">
      <PageHeader title="录入新门店" onBack={() => navigate('/stores')} />

      <nav className="partner-stepper">
        <div className="partner-stepper-inner">
          <div className="partner-stepper-line" aria-hidden>
            <div className="partner-stepper-line-fill" style={{ width: `${progress}%` }} />
          </div>
          {STEPS.map((label, i) => {
            const n = i + 1;
            const done = step > n;
            const active = step === n;
            return (
              <div key={label} className="partner-step">
                <div className={`partner-step-circle${done ? ' partner-step-circle--done' : ''}${active ? ' partner-step-circle--active' : ''}`}>
                  {done ? <span className="material-symbols-outlined" style={{ fontSize: 16, fontVariationSettings: "'FILL' 1" }}>check</span> : n}
                </div>
                <span className={`partner-step-label${active || done ? ' partner-step-label--active' : ''}`}>{label}</span>
              </div>
            );
          })}
        </div>
      </nav>

      {error && (
        <p className="partner-form-error" role="alert">{error}</p>
      )}

      {step === 1 && (
        <>
          <section className="partner-form-card">
            <div className="partner-section-title">
              <div className="partner-section-bar" />
              <h2 className="headline-md">门店基本信息</h2>
            </div>
            <div className="partner-field">
              <label>门店名称 <span className="text-primary">*</span></label>
              <div className="partner-field-input">
                <span className="material-symbols-outlined">store</span>
                <input placeholder="请输入门店名称" value={form.name} onChange={(e) => patchForm({ name: e.target.value })} />
              </div>
            </div>
            <div className="partner-field">
              <label>联系电话 <span className="text-primary">*</span></label>
              <div className="partner-field-input">
                <span className="material-symbols-outlined">call</span>
                <input type="tel" placeholder="请输入联系电话" value={form.phone} onChange={(e) => patchForm({ phone: e.target.value })} />
              </div>
            </div>
            <div className="partner-field">
              <label>区县 <span className="text-primary">*</span></label>
              <div className="partner-field-input">
                <span className="material-symbols-outlined">location_on</span>
                <input placeholder="请选择区县" value={form.district} onChange={(e) => patchForm({ district: e.target.value })} />
              </div>
            </div>
            <div className="partner-field">
              <label>详细地址 <span className="text-primary">*</span></label>
              <textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} />
            </div>
            <div className="partner-field">
              <label>门店简介</label>
              <textarea rows={4} placeholder="请输入门店简介 (10-500字)" value={form.intro} onChange={(e) => patchForm({ intro: e.target.value })} />
              <div style={{ textAlign: 'right', marginTop: 4 }}>
                <span className="label-md text-muted">{form.intro.length} / 500</span>
              </div>
            </div>
          </section>
          <div className="partner-info-banner">
            <div className="partner-bills-icon">
              <span className="material-symbols-outlined">verified_user</span>
            </div>
            <div>
              <h3 className="body-md text-primary" style={{ fontWeight: 700 }}>杜康合伙人身份认证</h3>
              <p className="label-md text-variant" style={{ marginTop: 4, lineHeight: 1.4 }}>
                填写内容将自动保存，退出后可继续录入。
              </p>
            </div>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div className="partner-section-title" style={{ padding: '0 20px', marginBottom: 16 }}>
            <div className="partner-bills-icon" style={{ background: '#ffdad7', borderRadius: 8, width: 40, height: 40 }}>
              <span className="material-symbols-outlined text-primary">photo_library</span>
            </div>
            <h2 className="headline-md">门店图片上传</h2>
          </div>

          <section className="partner-form-card">
            <h3 className="headline-md">门头照 *</h3>
            <p className="label-md text-muted" style={{ margin: '4px 0 12px' }}>至少1张，需包含完整招牌</p>
            <button type="button" className="partner-upload-dashed partner-upload-dashed--wide">
              <span className="material-symbols-outlined text-primary" style={{ fontSize: 36 }}>add_a_photo</span>
              <span className="text-primary" style={{ fontWeight: 500 }}>点击或拖拽上传</span>
            </button>
          </section>

          <section className="partner-form-card">
            <h3 className="headline-md">环境照片 *</h3>
            <p className="label-md text-muted" style={{ margin: '4px 0 12px' }}>至少3张，展示店内整洁环境</p>
            <div className="partner-upload-grid">
              {[0, 1, 2].map((i) => (
                <button key={i} type="button" className="partner-upload-dashed">
                  <span className="material-symbols-outlined text-primary">add_a_photo</span>
                  <span>添加照片</span>
                </button>
              ))}
            </div>
          </section>

          <section className="partner-form-card">
            <h3 className="headline-md">签约合同 *</h3>
            <p className="label-md text-muted" style={{ margin: '4px 0 12px' }}>拍照上传签约协议首页与盖章页</p>
            <button type="button" className="partner-upload-dashed" style={{ flexDirection: 'row', height: 96 }}>
              <div className="partner-bills-icon" style={{ background: '#ffb3ae' }}>
                <span className="material-symbols-outlined text-primary">description</span>
              </div>
              <div style={{ textAlign: 'left' }}>
                <span className="text-primary" style={{ fontWeight: 700, display: 'block' }}>上传合同副本</span>
                <span className="label-md text-muted">支持 JPG, PNG, PDF</span>
              </div>
            </button>
          </section>

          <div className="partner-info-banner" style={{ background: 'rgba(254,214,91,0.2)', borderColor: 'rgba(254,214,91,0.5)' }}>
            <span className="material-symbols-outlined text-secondary" style={{ fontSize: 18 }}>info</span>
            <p className="label-md" style={{ lineHeight: 1.5, color: 'var(--color-on-secondary-container)' }}>
              温馨提示：preV1 占位上传，可直接下一步。
            </p>
          </div>
        </>
      )}

      {step === 3 && (
        <>
          <div className="partner-section-title" style={{ padding: '0 20px', marginBottom: 16 }}>
            <span className="material-symbols-outlined text-primary">account_balance</span>
            <h2 className="headline-md">结算信息配置</h2>
          </div>
          <section className="partner-form-card">
            <div className="partner-field">
              <label>户主姓名 *</label>
              <input className="partner-field-input partner-field-input--block" placeholder="请输入银行卡实名姓名" value={form.bankAccountName} onChange={(e) => patchForm({ bankAccountName: e.target.value })} />
            </div>
            <div className="partner-field">
              <label>银行卡号 *</label>
              <input className="partner-field-input partner-field-input--block" placeholder="请输入16-19位银行卡号" value={form.bankAccountNo} onChange={(e) => patchForm({ bankAccountNo: e.target.value })} />
            </div>
            <div className="partner-field">
              <label>开户支行 *</label>
              <input className="partner-field-input partner-field-input--block" placeholder="例如：中国工商银行洛阳分行" value={form.bankBranch} onChange={(e) => patchForm({ bankBranch: e.target.value })} />
            </div>
          </section>
          <div className="partner-info-banner" style={{ background: 'rgba(254,214,91,0.15)', borderColor: 'rgba(254,214,91,0.3)' }}>
            <span className="material-symbols-outlined text-secondary">info</span>
            <p className="body-md" style={{ color: 'var(--color-on-secondary-container)' }}>
              请确保银行卡信息准确，以免影响每月的餐费结算。
            </p>
          </div>
        </>
      )}

      <footer className="partner-sticky-footer">
        {step > 1 && (
          <button type="button" className="partner-btn-outline" onClick={() => goStep(step - 1)}>上一步</button>
        )}
        {step < 3 ? (
          <button type="button" className="partner-btn-primary" onClick={handleNext}>
            <span>下一步</span>
            <span className="material-symbols-outlined" style={{ fontSize: 20 }}>navigate_next</span>
          </button>
        ) : (
          <button type="button" className="partner-btn-primary" onClick={submit}>提交审核</button>
        )}
      </footer>
    </div>
  );
}
