import { useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import type { Room, Point } from '@house-plan-maker/shared';
import { Card, CardHeader } from '../ui/Card';
import { Button } from '../ui/Button';
import styles from './room-card.module.css';

interface RoomCardProps {
  room: Room;
  apartmentId: string;
  onEdit: (room: Room) => void;
  onDelete: (room: Room) => void;
  onClone: (room: Room) => void;
  cloneLoading?: boolean;
}

function ShapePreview({ shape }: { shape: readonly Point[] }) {
  if (shape.length < 3) {
    return (
      <svg className={styles.previewSvg} viewBox="0 0 72 72">
        <rect
          x="12"
          y="12"
          width="48"
          height="48"
          fill="none"
          stroke="var(--color-accent-400)"
          strokeWidth="1.5"
          strokeDasharray="4 2"
        />
      </svg>
    );
  }

  const xs = shape.map((p) => p.x);
  const ys = shape.map((p) => p.y);
  const minX = Math.min(...xs);
  const maxX = Math.max(...xs);
  const minY = Math.min(...ys);
  const maxY = Math.max(...ys);
  const shapeWidth = maxX - minX || 1;
  const shapeHeight = maxY - minY || 1;

  const padding = 8;
  const availableSize = 72 - padding * 2;
  const scale = Math.min(availableSize / shapeWidth, availableSize / shapeHeight);
  const offsetX = padding + (availableSize - shapeWidth * scale) / 2;
  const offsetY = padding + (availableSize - shapeHeight * scale) / 2;

  const points = shape
    .map((p) => {
      const sx = (p.x - minX) * scale + offsetX;
      const sy = (p.y - minY) * scale + offsetY;
      return `${sx},${sy}`;
    })
    .join(' ');

  return (
    <svg className={styles.previewSvg} viewBox="0 0 72 72">
      <polygon
        points={points}
        fill="var(--color-accent-50)"
        stroke="var(--color-accent-500)"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function RoomCard({ room, apartmentId, onEdit, onDelete, onClone, cloneLoading = false }: RoomCardProps) {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();

  const handleClick = () => {
    navigate(`/apartments/${apartmentId}/rooms/${room.id}/editor`);
  };

  const handleEdit = (event: React.MouseEvent) => {
    event.stopPropagation();
    onEdit(room);
  };

  const handleDelete = (event: React.MouseEvent) => {
    event.stopPropagation();
    onDelete(room);
  };

  const handleClone = (event: React.MouseEvent) => {
    event.stopPropagation();
    onClone(room);
  };

  const cloneLabel = i18n.exists('roomCard.clone') ? t('roomCard.clone') : 'Clone';

  const dimensions =
    room.width != null && room.height != null
      ? t('rooms.dimensions', { width: room.width, height: room.height })
      : t('rooms.vertices', { count: room.shape.length });

  return (
    <Card interactive className={styles.card} onClick={handleClick}>
      <CardHeader>
        <div className={styles.cardBody}>
          <div className={styles.preview}>
            <ShapePreview shape={room.shape} />
          </div>
          <div className={styles.info}>
            <h4 className={styles.name}>{room.name}</h4>
            <p className={styles.dimensions}>{dimensions}</p>
            <div className={styles.details}>
              <span>{t('rooms.wallHeight', { value: room.wallHeight })}</span>
              <span>{t('rooms.plinth', { value: room.plinthHeight })}</span>
            </div>
          </div>
        </div>
        <div className={styles.actions}>
          <Button variant="ghost" size="sm" onClick={handleEdit} aria-label={t('roomCard.edit')}>
            {t('roomCard.edit')}
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleClone}
            aria-label={cloneLabel}
            disabled={cloneLoading}
          >
            {cloneLoading ? '…' : cloneLabel}
          </Button>
          <Button variant="ghost" size="sm" onClick={handleDelete} aria-label={t('roomCard.delete')}>
            {t('roomCard.delete')}
          </Button>
        </div>
      </CardHeader>
    </Card>
  );
}
