import { Head, useForm } from '@inertiajs/react';
import { useState } from 'react';
import { TextInput } from '@/Components/Forms/TextInput';

type MissingField = { key: string; label: string };
type ParentMode = 'none' | 'father' | 'mother' | 'either' | 'both';

type Props = {
  requiredFields?: string[];
  missingFields?: MissingField[];
  mustChangePassword?: boolean;
  isForced?: boolean;
  isStudent?: boolean;
  parentMode?: ParentMode;
};

export default function CompleteProfile({
  requiredFields = [],
  missingFields = [],
  mustChangePassword = false,
  isForced = true,
  isStudent = false,
  parentMode = 'none',
}: Props) {
  const form = useForm({
    mobile: '',
    national_code: '',
    father_mobile: '',
    mother_mobile: '',
    home_phone: '',
    address: '',
  });

  // 'either' collects one number; this picks which parent it belongs to.
  const [eitherParent, setEitherParent] = useState<'father' | 'mother'>('father');

  const required = new Set(requiredFields);
  const mark = (key: string) => (required.has(key) ? ' *' : '');
  const shows = (key: string) => required.has(key) || isStudent;

  function setEitherValue(value: string) {
    // Only ever hold a number in the selected parent's field.
    form.setData((data) => ({
      ...data,
      father_mobile: eitherParent === 'father' ? value : '',
      mother_mobile: eitherParent === 'mother' ? value : '',
    }));
  }

  function switchEitherParent(next: 'father' | 'mother') {
    const current = eitherParent === 'father' ? form.data.father_mobile : form.data.mother_mobile;
    setEitherParent(next);
    form.setData((data) => ({
      ...data,
      father_mobile: next === 'father' ? current : '',
      mother_mobile: next === 'mother' ? current : '',
    }));
  }

  const eitherValue = eitherParent === 'father' ? form.data.father_mobile : form.data.mother_mobile;
  const eitherError = form.errors.father_mobile ?? form.errors.mother_mobile;

  return (
    <main className="auth-page">
      <Head title="تکمیل اطلاعات">
        <meta name="description" content="تکمیل اطلاعات ضروری کاربر در اولین ورود به دانشیار من." />
      </Head>

      <section className="auth-card wide">
        <h1>تکمیل اطلاعات</h1>
        <p>
          {isForced
            ? 'برای ورود به پنل، اطلاعات ضروری را تکمیل کنید.'
            : 'این بخش اختیاری است و هر زمان خواستید می‌توانید کاملش کنید.'}
        </p>

        {(missingFields.length > 0 || mustChangePassword) && (
          <div className="form-info" style={{ marginBottom: '1rem' }}>
            {mustChangePassword && <span>تغییر رمز عبور</span>}
            {missingFields.map((field) => <span key={field.key}>{field.label}</span>)}
          </div>
        )}

        <form onSubmit={(event) => { event.preventDefault(); form.post('/complete-profile'); }}>
          <div className="profile-field-row">
            <TextInput
              label={`موبایل${mark('mobile')}`}
              value={form.data.mobile}
              onChange={(e) => form.setData('mobile', e.target.value)}
              error={form.errors.mobile}
              placeholder="۰۹۱۲۳۴۵۶۷۸۹"
            />
            {shows('national_code') && (
              <TextInput
                label={`کد ملی${mark('national_code')}`}
                value={form.data.national_code}
                onChange={(e) => form.setData('national_code', e.target.value)}
                error={form.errors.national_code}
              />
            )}
          </div>

          {/* Parent numbers — layout depends on what the school requires. */}
          {parentMode === 'both' && (
            <div className="profile-field-row">
              <TextInput
                label="موبایل پدر *"
                value={form.data.father_mobile}
                onChange={(e) => form.setData('father_mobile', e.target.value)}
                error={form.errors.father_mobile}
                placeholder="۰۹۱۲۳۴۵۶۷۸۹"
              />
              <TextInput
                label="موبایل مادر *"
                value={form.data.mother_mobile}
                onChange={(e) => form.setData('mother_mobile', e.target.value)}
                error={form.errors.mother_mobile}
                placeholder="۰۹۱۲۳۴۵۶۷۸۹"
              />
            </div>
          )}

          {parentMode === 'father' && (
            <TextInput
              label="موبایل پدر *"
              value={form.data.father_mobile}
              onChange={(e) => form.setData('father_mobile', e.target.value)}
              error={form.errors.father_mobile}
              placeholder="۰۹۱۲۳۴۵۶۷۸۹"
            />
          )}

          {parentMode === 'mother' && (
            <TextInput
              label="موبایل مادر *"
              value={form.data.mother_mobile}
              onChange={(e) => form.setData('mother_mobile', e.target.value)}
              error={form.errors.mother_mobile}
              placeholder="۰۹۱۲۳۴۵۶۷۸۹"
            />
          )}

          {parentMode === 'either' && (
            <div className="form-field">
              <span>موبایل پدر یا مادر *</span>
              <div className="parent-either">
                <select
                  className="form-control parent-either-select"
                  value={eitherParent}
                  onChange={(e) => switchEitherParent(e.target.value as 'father' | 'mother')}
                  aria-label="نسبت"
                >
                  <option value="father">پدر</option>
                  <option value="mother">مادر</option>
                </select>
                <input
                  className="form-control"
                  value={eitherValue}
                  onChange={(e) => setEitherValue(e.target.value)}
                  placeholder="۰۹۱۲۳۴۵۶۷۸۹"
                  inputMode="numeric"
                  aria-label="شماره موبایل ولی"
                />
              </div>
              {eitherError
                ? <small className="form-error">{eitherError}</small>
                : <small className="form-hint">یکی از این دو شماره کافی است.</small>}
            </div>
          )}

          {shows('home_phone') && (
            <div className="profile-field-row">
              <TextInput
                label={`شماره خانه${mark('home_phone')}`}
                value={form.data.home_phone}
                onChange={(e) => form.setData('home_phone', e.target.value)}
                error={form.errors.home_phone}
              />
            </div>
          )}

          {shows('address') && (
            <TextInput
              label={`آدرس${mark('address')}`}
              value={form.data.address}
              onChange={(e) => form.setData('address', e.target.value)}
              error={form.errors.address}
            />
          )}

          <button className="btn btn-primary full" disabled={form.processing}>ذخیره و ورود</button>
        </form>
      </section>
    </main>
  );
}
