'use client';

import { useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import { Input } from '@/components/ui/shared/Input';
import {
  ResponsiveDialogOverlay,
  ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
import { CreatePatientInput } from '@/types/patient';
import { isValidMobile, normalizeMobile } from '@/lib/phone';

interface CreatePatientModalProps {
  isOpen: boolean;
  formData: CreatePatientInput;
  onChange: (patch: Partial<CreatePatientInput>) => void;
  onSubmit: () => void;
  onClose: () => void;
  loading?: boolean;
  /** Inline panel on Patients page; centered dialog on Appointments. */
  variant?: 'inline' | 'dialog';
}

type FieldErrors = Partial<Record<'firstName' | 'lastName' | 'mobile' | 'email', string>>;

function CreatePatientFormFields({
  formData,
  onChange,
  onSubmit,
  onClose,
  loading,
  showCancel,
}: {
  formData: CreatePatientInput;
  onChange: (patch: Partial<CreatePatientInput>) => void;
  onSubmit: () => void;
  onClose: () => void;
  loading: boolean;
  showCancel: boolean;
}) {
  const t = useTranslations('patients');
  const tCommon = useTranslations('common');
  const tValidation = useTranslations('validation');
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});

  const requiredMark = t('requiredMark');

  const validate = (): boolean => {
    const nextErrors: FieldErrors = {};

    if (!formData.firstName?.trim()) {
      nextErrors.firstName = t('firstNameRequired');
    }
    if (!formData.lastName?.trim()) {
      nextErrors.lastName = t('lastNameRequired');
    }
    if (!formData.mobile?.trim()) {
      nextErrors.mobile = tValidation('mobileRequired');
    } else if (!isValidMobile(normalizeMobile(formData.mobile) ?? '')) {
      nextErrors.mobile = tValidation('mobileInvalid');
    }

    if (formData.email?.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email.trim())) {
      nextErrors.email = tValidation('emailInvalid');
    }

    setFieldErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const handleSubmit = () => {
    if (!validate()) {
      return;
    }
    onSubmit();
  };

  const isSubmitDisabled = useMemo(
    () =>
      !formData.firstName?.trim() ||
      !formData.lastName?.trim() ||
      !isValidMobile(normalizeMobile(formData.mobile || '') ?? ''),
    [formData.firstName, formData.lastName, formData.mobile],
  );

  const mobileDisplayError = useMemo(() => {
    if (fieldErrors.mobile) {
      return fieldErrors.mobile;
    }
    const raw = formData.mobile?.trim() ?? '';
    if (!raw) {
      if (formData.firstName?.trim() && formData.lastName?.trim()) {
        return tValidation('mobileRequired');
      }
      return undefined;
    }
    if (!isValidMobile(normalizeMobile(formData.mobile) ?? '')) {
      return tValidation('mobileInvalid');
    }
    return undefined;
  }, [
    fieldErrors.mobile,
    formData.mobile,
    formData.firstName,
    formData.lastName,
    tValidation,
  ]);

  return (
    <>
      <p className="text-sm text-text-muted">{t('requiredFieldsHint')}</p>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <Input
          label={`${t('firstName')} ${requiredMark}`}
          value={formData.firstName || ''}
          onChange={(e) => {
            onChange({ firstName: e.target.value });
            if (fieldErrors.firstName) {
              setFieldErrors((prev) => ({ ...prev, firstName: undefined }));
            }
          }}
          required
          error={fieldErrors.firstName}
        />
        <Input
          label={`${t('lastName')} ${requiredMark}`}
          value={formData.lastName || ''}
          onChange={(e) => {
            onChange({ lastName: e.target.value });
            if (fieldErrors.lastName) {
              setFieldErrors((prev) => ({ ...prev, lastName: undefined }));
            }
          }}
          required
          error={fieldErrors.lastName}
        />
        <Input
          label={`${t('mobile')} ${requiredMark}`}
          value={formData.mobile || ''}
          onChange={(e) => {
            onChange({ mobile: e.target.value });
            if (fieldErrors.mobile) {
              setFieldErrors((prev) => ({ ...prev, mobile: undefined }));
            }
          }}
          placeholder={t('mobilePlaceholder')}
          required
          error={mobileDisplayError}
        />
        <Input
          label={t('emailOptional')}
          type="text"
          inputMode="email"
          autoComplete="email"
          value={formData.email || ''}
          onChange={(e) => {
            onChange({ email: e.target.value });
            if (fieldErrors.email) {
              setFieldErrors((prev) => ({ ...prev, email: undefined }));
            }
          }}
          error={fieldErrors.email}
        />
      </div>

      <div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center">
        <Button
          variant="primary"
          onClick={handleSubmit}
          isLoading={loading}
          fullWidth
          className="sm:w-auto"
          disabled={isSubmitDisabled}
        >
          {t('savePatient')}
        </Button>
        {showCancel && (
          <Button variant="ghost" onClick={onClose} fullWidth className="sm:w-auto">
            {tCommon('cancel')}
          </Button>
        )}
      </div>
    </>
  );
}

export function CreatePatientModal({
  isOpen,
  formData,
  onChange,
  onSubmit,
  onClose,
  loading = false,
  variant = 'inline',
}: CreatePatientModalProps) {
  const t = useTranslations('patients');

  if (!isOpen) {
    return null;
  }

  if (variant === 'dialog') {
    return (
      <ResponsiveDialogOverlay onBackdropClick={onClose} zIndexClass="z-[60]" className="bg-black/55">
        <ResponsiveDialogPanel
          maxWidthClass="sm:max-w-2xl"
          role="dialog"
          aria-modal="true"
          aria-labelledby="create-patient-dialog-title"
          className="surface-card space-y-4"
        >
          <div className="flex items-start justify-between gap-2">
            <h2
              id="create-patient-dialog-title"
              className="text-lg font-semibold text-text-primary pr-2"
            >
              {t('dialogTitle')}
            </h2>
            <DialogCloseButton onClick={onClose} />
          </div>

          <CreatePatientFormFields
            formData={formData}
            onChange={onChange}
            onSubmit={onSubmit}
            onClose={onClose}
            loading={loading}
            showCancel={false}
          />
        </ResponsiveDialogPanel>
      </ResponsiveDialogOverlay>
    );
  }

  return (
    <div className="surface-card p-3 sm:p-4 space-y-3">
      <CreatePatientFormFields
        formData={formData}
        onChange={onChange}
        onSubmit={onSubmit}
        onClose={onClose}
        loading={loading}
        showCancel
      />
    </div>
  );
}
