import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import { PARTNER_STAFF_ROLE_LABELS, PartnerStaffRole } from '@dukang/shared-types';
import { createPartnerStaff, sendStaffAddSms } from '../lib/staff';
import { toastError, toastSuccess } from '../lib/toast';

const ROLE_OPTIONS = Object.values(PartnerStaffRole);

export default function StaffCreatePage() {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [staffRole, setStaffRole] = useState<PartnerStaffRole>(PartnerStaffRole.INTERNAL);
  const [sending, setSending] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [msg, setMsg] = useState('');

  async function sendCode() {
    if (!/^1[3-9]\d{9}$/.test(phone.trim())) {
      const text = '请输入正确的11位手机号';
      setMsg(text);
      toastError(text);
      return;
    }
    setSending(true);
    setMsg('');
    try {
      await sendStaffAddSms(phone.trim());
      setMsg('验证码已发送');
    } catch {
      /* request 已 toast */
    } finally {
      setSending(false);
    }
  }

  async function submit() {
    if (!name.trim()) {
      const text = '请填写真实姓名';
      setMsg(text);
      toastError(text);
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phone.trim())) {
      const text = '请输入正确的11位手机号';
      setMsg(text);
      toastError(text);
      return;
    }
    if (!code.trim()) {
      const text = '请输入验证码';
      setMsg(text);
      toastError(text);
      return;
    }
    setSubmitting(true);
    setMsg('');
    try {
      await createPartnerStaff({
        name: name.trim(),
        phone: phone.trim(),
        staffRole,
        code: code.trim(),
      });
      toastSuccess('子账号创建成功');
      navigate('/center/staff');
    } catch {
      /* request 已 toast */
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="page-no-tab partner-staff-create-page">
      <PageHeader title="添加子账号" onBack={() => navigate('/center/staff')} />

      <main style={{ padding: '16px 20px 120px' }}>
        {msg && <p className="partner-form-error" role="alert" style={{ marginBottom: 12 }}>{msg}</p>}

        <div className="partner-form-card">
          <label className="partner-form-label">真实姓名 *</label>
          <div className="partner-form-input-wrap">
            <input
              className="partner-form-input"
              placeholder="请输入员工姓名"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <span className="material-symbols-outlined">person</span>
          </div>
        </div>

        <div className="partner-form-card">
          <label className="partner-form-label">手机号码 *</label>
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              className="partner-form-input"
              placeholder="请输入11位手机号"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              inputMode="numeric"
            />
            <button type="button" className="btn btn-outline" disabled={sending} onClick={() => void sendCode()}>
              {sending ? '发送中' : '获取验证码'}
            </button>
          </div>
          <input
            className="partner-form-input"
            style={{ marginTop: 8 }}
            placeholder="验证码"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            inputMode="numeric"
          />
        </div>

        <div className="partner-form-card">
          <label className="partner-form-label">分配角色 *</label>
          <div className="partner-form-input-wrap">
            <select
              className="partner-form-input"
              value={staffRole}
              onChange={(e) => setStaffRole(e.target.value as PartnerStaffRole)}
            >
              {ROLE_OPTIONS.map((role) => (
                <option key={role} value={role}>{PARTNER_STAFF_ROLE_LABELS[role]}</option>
              ))}
            </select>
            <span className="material-symbols-outlined">expand_more</span>
          </div>
        </div>

        <p className="label-md text-muted" style={{ marginTop: 16, textAlign: 'center' }}>
          创建即代表同意合伙人管理协议。子账号默认禁用，需手动启用。
        </p>
      </main>

      <div className="partner-sticky-footer">
        <button type="button" className="partner-btn-primary" disabled={submitting} onClick={() => void submit()}>
          <span className="material-symbols-outlined">person_add</span>
          {submitting ? '创建中...' : '确认创建'}
        </button>
      </div>
    </div>
  );
}
