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

type ShapeType = 'rectangular' | 'custom';

interface RoomFormData {
  name: string;
  shapeType: ShapeType;
  width: string;
  height: string;
  wallHeight: string;
  plinthHeight: string;
  plinthThickness: string;
}

interface RoomFormModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: {
    name: string;
    shape: readonly Point[];
    width: number | null;
    height: number | null;
    wallHeight: number;
    plinthHeight: number;
    plinthThickness: number;
  }) => void;
  room?: Room | null;
  loading?: boolean;
}

interface FormErrors {
  name?: string;
  width?: string;
  height?: string;
  wallHeight?: string;
  plinthHeight?: string;
  plinthThickness?: string;
}

function rectangularShape(w: number, h: number): readonly Point[] {
  return [
    { x: 0, y: 0 },
    { x: w, y: 0 },
    { x: w, y: h },
    { x: 0, y: h },
  ];
}

function isRectangular(room: Room): boolean {
  return room.width != null && room.height != null;
}

export function RoomFormModal({
  open,
  onClose,
  onSubmit,
  room,
  loading = false,
}: RoomFormModalProps) {
  const { t } = useTranslation();
  const [form, setForm] = useState<RoomFormData>({
    name: '',
    shapeType: 'rectangular',
    width: '',
    height: '',
    wallHeight: '2.5',
    plinthHeight: '0.06',
    plinthThickness: '0.01',
  });
  const [errors, setErrors] = useState<FormErrors>({});

  const isEditing = room != null;

  useEffect(() => {
    if (open) {
      if (room) {
        setForm({
          name: room.name,
          shapeType: isRectangular(room) ? 'rectangular' : 'custom',
          width: room.width != null ? String(room.width) : '',
          height: room.height != null ? String(room.height) : '',
          wallHeight: String(room.wallHeight),
          plinthHeight: String(room.plinthHeight),
          plinthThickness: String(room.plinthThickness),
        });
      } else {
        setForm({
          name: '',
          shapeType: 'rectangular',
          width: '',
          height: '',
          wallHeight: '2.5',
          plinthHeight: '0.06',
          plinthThickness: '0.01',
        });
      }
      setErrors({});
    }
  }, [open, room]);

  const updateField = (field: keyof RoomFormData, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const validate = (): boolean => {
    const fieldErrors: FormErrors = {};

    const width = form.width.trim() ? Number(form.width) : null;
    const height = form.height.trim() ? Number(form.height) : null;
    const wallHeight = Number(form.wallHeight) || 2.5;
    const plinthHeight = form.plinthHeight.trim() ? Number(form.plinthHeight) : 0.06;
    const plinthThickness = form.plinthThickness.trim() ? Number(form.plinthThickness) : 0.01;

    let shape: readonly Point[] | undefined;
    if (form.shapeType === 'rectangular') {
      if (!width || width <= 0) {
        fieldErrors.width = t('roomForm.widthError');
      }
      if (!height || height <= 0) {
        fieldErrors.height = t('roomForm.heightError');
      }
      if (width && height && width > 0 && height > 0) {
        shape = rectangularShape(width, height);
      }
    } else {
      // Custom polygon: keep existing shape for editing, empty for new
      shape = room?.shape;
    }

    const result = createRoomSchema.safeParse({
      name: form.name.trim(),
      shape,
      width,
      height,
      wallHeight,
      plinthHeight,
      plinthThickness,
    });

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

    if (Object.keys(fieldErrors).length > 0) {
      setErrors(fieldErrors);
      return false;
    }

    setErrors({});
    return true;
  };

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    if (!validate()) return;

    const width = form.width.trim() ? Number(form.width) : null;
    const height = form.height.trim() ? Number(form.height) : null;
    const wallHeight = Number(form.wallHeight) || 2.5;
    const plinthHeight = form.plinthHeight.trim() ? Number(form.plinthHeight) : 0.06;
    const plinthThickness = form.plinthThickness.trim() ? Number(form.plinthThickness) : 0.01;

    let shape: readonly Point[];
    if (form.shapeType === 'rectangular' && width && height) {
      shape = rectangularShape(width, height);
    } else {
      shape = room?.shape ?? [];
    }

    onSubmit({
      name: form.name.trim(),
      shape,
      width,
      height,
      wallHeight,
      plinthHeight,
      plinthThickness,
    });
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? t('roomForm.titleEdit') : t('roomForm.titleNew')}
      footer={
        <>
          <Button variant="secondary" onClick={onClose} disabled={loading}>
            {t('common.cancel')}
          </Button>
          <Button type="submit" form="room-form" disabled={loading}>
            {loading
              ? isEditing
                ? t('roomForm.saving')
                : t('roomForm.creating')
              : isEditing
                ? t('roomForm.saveChanges')
                : t('roomForm.createRoom')}
          </Button>
        </>
      }
    >
      <form id="room-form" className={styles.form} onSubmit={handleSubmit}>
        <Input
          label={t('roomForm.name')}
          value={form.name}
          onChange={(e) => updateField('name', e.target.value)}
          error={errors.name}
          placeholder={t('roomForm.namePlaceholder')}
          autoFocus
          required
        />

        {/* Shape type selector */}
        <div className={styles.shapeSelector}>
          <span className={styles.shapeLabel}>{t('roomForm.shape')}</span>
          <div className={styles.shapeOptions}>
            <button
              type="button"
              className={[
                styles.shapeOption,
                form.shapeType === 'rectangular' ? styles.shapeOptionActive : undefined,
              ]
                .filter(Boolean)
                .join(' ')}
              onClick={() => updateField('shapeType', 'rectangular')}
            >
              {t('roomForm.rectangular')}
            </button>
            <button
              type="button"
              className={[
                styles.shapeOption,
                form.shapeType === 'custom' ? styles.shapeOptionActive : undefined,
              ]
                .filter(Boolean)
                .join(' ')}
              onClick={() => updateField('shapeType', 'custom')}
            >
              {t('roomForm.customPolygon')}
            </button>
          </div>
        </div>

        {form.shapeType === 'rectangular' ? (
          <div className={styles.row}>
            <Input
              label={t('roomForm.width')}
              type="number"
              value={form.width}
              onChange={(e) => updateField('width', e.target.value)}
              error={errors.width}
              placeholder={t('roomForm.widthPlaceholder')}
              min="0.1"
              step="0.01"
              required
            />
            <Input
              label={t('roomForm.height')}
              type="number"
              value={form.height}
              onChange={(e) => updateField('height', e.target.value)}
              error={errors.height}
              placeholder={t('roomForm.heightPlaceholder')}
              min="0.1"
              step="0.01"
              required
            />
          </div>
        ) : (
          <div className={styles.customNote}>
            {t('roomForm.customNote')}
            {isEditing && room?.shape && room.shape.length > 0
              ? t('roomForm.currentVertices', { count: room.shape.length })
              : t('roomForm.defaultShape')}
          </div>
        )}

        <span className={styles.sectionTitle}>{t('roomForm.wallProperties')}</span>

        <Input
          label={t('roomForm.wallHeight')}
          type="number"
          value={form.wallHeight}
          onChange={(e) => updateField('wallHeight', e.target.value)}
          error={errors.wallHeight}
          placeholder="2.5"
          min="0.1"
          step="0.01"
        />

        <span className={styles.sectionTitle}>{t('roomForm.plinthProperties')}</span>

        <div className={styles.row}>
          <Input
            label={t('roomForm.plinthHeight')}
            type="number"
            value={form.plinthHeight}
            onChange={(e) => updateField('plinthHeight', e.target.value)}
            error={errors.plinthHeight}
            placeholder="0.06"
            min="0"
            step="0.001"
            hint={t('roomForm.plinthHeightHint')}
          />
          <Input
            label={t('roomForm.plinthThickness')}
            type="number"
            value={form.plinthThickness}
            onChange={(e) => updateField('plinthThickness', e.target.value)}
            error={errors.plinthThickness}
            placeholder="0.01"
            min="0"
            step="0.001"
            hint={t('roomForm.plinthThicknessHint')}
          />
        </div>
      </form>
    </Modal>
  );
}
