import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import type { Apartment } from '@house-plan-maker/shared';
import { createApartmentSchema } from '@house-plan-maker/shared';
import { Modal } from '../ui/Modal';
import { Input } from '../ui/Input';
import { Button } from '../ui/Button';
import styles from './apartment-form-modal.module.css';

interface ApartmentFormModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: { name: string; address: string; totalArea: string }) => void;
  apartment?: Apartment | null;
  loading?: boolean;
}

interface FormErrors {
  name?: string;
  address?: string;
  totalArea?: string;
}

export function ApartmentFormModal({
  open,
  onClose,
  onSubmit,
  apartment,
  loading = false,
}: ApartmentFormModalProps) {
  const { t } = useTranslation();
  const [name, setName] = useState('');
  const [address, setAddress] = useState('');
  const [totalArea, setTotalArea] = useState('');
  const [errors, setErrors] = useState<FormErrors>({});

  const isEditing = apartment != null;

  useEffect(() => {
    if (open) {
      setName(apartment?.name ?? '');
      setAddress(apartment?.address ?? '');
      setTotalArea(apartment?.totalArea != null ? String(apartment.totalArea) : '');
      setErrors({});
    }
  }, [open, apartment]);

  const validate = (): boolean => {
    const result = createApartmentSchema.safeParse({
      name: name.trim(),
      address: address.trim() || null,
      totalArea: totalArea.trim() ? Number(totalArea) : null,
    });

    if (!result.success) {
      const fieldErrors: FormErrors = {};
      for (const issue of result.error.issues) {
        const field = issue.path[0] as keyof FormErrors;
        if (!fieldErrors[field]) {
          fieldErrors[field] = issue.message;
        }
      }
      setErrors(fieldErrors);
      return false;
    }

    setErrors({});
    return true;
  };

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    if (validate()) {
      onSubmit({ name: name.trim(), address: address.trim(), totalArea: totalArea.trim() });
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? t('apartmentForm.titleEdit') : t('apartmentForm.titleNew')}
      footer={
        <>
          <Button variant="secondary" onClick={onClose} disabled={loading}>
            {t('common.cancel')}
          </Button>
          <Button
            type="submit"
            form="apartment-form"
            disabled={loading}
          >
            {loading
              ? isEditing
                ? t('apartmentForm.saving')
                : t('apartmentForm.creating')
              : isEditing
                ? t('apartmentForm.saveChanges')
                : t('apartmentForm.createApartment')}
          </Button>
        </>
      }
    >
      <form id="apartment-form" className={styles.form} onSubmit={handleSubmit}>
        <Input
          label={t('apartmentForm.name')}
          value={name}
          onChange={(e) => setName(e.target.value)}
          error={errors.name}
          placeholder={t('apartmentForm.namePlaceholder')}
          autoFocus
          required
        />
        <Input
          label={t('apartmentForm.address')}
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          error={errors.address}
          placeholder={t('apartmentForm.addressPlaceholder')}
        />
        <Input
          label={t('apartmentForm.totalArea')}
          type="number"
          value={totalArea}
          onChange={(e) => setTotalArea(e.target.value)}
          error={errors.totalArea}
          placeholder={t('apartmentForm.totalAreaPlaceholder')}
          min="0"
          step="0.01"
        />
      </form>
    </Modal>
  );
}
