import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import type { Apartment } from '@house-plan-maker/shared';
import {
  getApartments,
  createApartment,
  updateApartment,
  deleteApartment,
} from '../api/client';
import { Button } from '../components/ui/Button';
import { LoadingSpinner } from '../components/ui/LoadingSpinner';
import { ErrorBanner } from '../components/ui/ErrorBanner';
import { EmptyState } from '../components/ui/EmptyState';
import { ApartmentCard } from '../components/apartments/ApartmentCard';
import { ApartmentFormModal } from '../components/apartments/ApartmentFormModal';
import { ConfirmDialog } from '../components/shared/ConfirmDialog';
import styles from './apartment-list-page.module.css';

export function ApartmentListPage() {
  const { t } = useTranslation();
  const [apartments, setApartments] = useState<readonly Apartment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Form modal state
  const [formOpen, setFormOpen] = useState(false);
  const [editingApartment, setEditingApartment] = useState<Apartment | null>(null);
  const [formLoading, setFormLoading] = useState(false);

  // Delete dialog state
  const [deleteTarget, setDeleteTarget] = useState<Apartment | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  const fetchApartments = useCallback(async () => {
    try {
      setError(null);
      const list = await getApartments();
      setApartments(list);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : t('apartments.error.load');
      setError(message);
    } finally {
      setLoading(false);
    }
  }, [t]);

  useEffect(() => {
    fetchApartments();
  }, [fetchApartments]);

  const handleCreate = () => {
    setEditingApartment(null);
    setFormOpen(true);
  };

  const handleEdit = (apartment: Apartment) => {
    setEditingApartment(apartment);
    setFormOpen(true);
  };

  const handleFormSubmit = async (data: {
    name: string;
    address: string;
    totalArea: string;
  }) => {
    setFormLoading(true);
    try {
      const payload = {
        name: data.name,
        address: data.address || null,
        totalArea: data.totalArea ? Number(data.totalArea) : null,
      };

      if (editingApartment) {
        await updateApartment(editingApartment.id, payload);
      } else {
        await createApartment(payload);
      }

      setFormOpen(false);
      await fetchApartments();
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : t('apartments.error.operation');
      setError(message);
    } finally {
      setFormLoading(false);
    }
  };

  const handleDeleteClick = (apartment: Apartment) => {
    setDeleteTarget(apartment);
  };

  const handleDeleteConfirm = async () => {
    if (!deleteTarget) return;
    setDeleteLoading(true);
    try {
      await deleteApartment(deleteTarget.id);
      setDeleteTarget(null);
      await fetchApartments();
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : t('apartments.error.delete');
      setError(message);
    } finally {
      setDeleteLoading(false);
    }
  };

  if (loading) {
    return <LoadingSpinner />;
  }

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <h1 className={styles.title}>{t('apartments.title')}</h1>
        <Button onClick={handleCreate}>{t('apartments.new')}</Button>
      </div>

      {error && <ErrorBanner message={error} onDismiss={() => setError(null)} />}

      {apartments.length === 0 && !error ? (
        <EmptyState
          title={t('apartments.empty.title')}
          description={t('apartments.empty.description')}
          action={
            <Button onClick={handleCreate}>{t('apartments.create')}</Button>
          }
        />
      ) : (
        <div className={styles.grid}>
          {apartments.map((apt) => (
            <ApartmentCard
              key={apt.id}
              apartment={apt}
              roomCount={apt.roomCount ?? 0}
              onEdit={handleEdit}
              onDelete={handleDeleteClick}
            />
          ))}
        </div>
      )}

      <ApartmentFormModal
        open={formOpen}
        onClose={() => setFormOpen(false)}
        onSubmit={handleFormSubmit}
        apartment={editingApartment}
        loading={formLoading}
      />

      <ConfirmDialog
        open={deleteTarget != null}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDeleteConfirm}
        title={t('apartments.delete.title')}
        message={t('apartments.delete.message', { name: deleteTarget?.name ?? '' })}
        loading={deleteLoading}
      />
    </div>
  );
}
