// ─────────────────────────────────────────────────────────────────────────────
// Ultra Image Cropper 2.0 — Crop Panel
// ─────────────────────────────────────────────────────────────────────────────

import React from 'react';
import type { AspectRatio, CropShape, GridOverlay } from '@/types';
import { useCanvasStore, useHistoryStore } from '@/store';
import { useCanvas } from '@/hooks/useCanvas';
import { ratioToNumber } from '@/utils/contextPresets';
import { useTranslation } from '@/i18n/useTranslation';

const RATIO_OPTIONS: { value: AspectRatio; label: string }[] = [
  { value: 'free',  label: 'Free'  },
  { value: '1:1',   label: '1:1'   },
  { value: '16:9',  label: '16:9'  },
  { value: '4:3',   label: '4:3'   },
  { value: '3:2',   label: '3:2'   },
  { value: '9:16',  label: '9:16'  },
  { value: '3:1',   label: '3:1'   },
];

export const CropPanel: React.FC = () => {
  const t = useTranslation();
  const { crop, setCrop, resetCrop, gridOverlay, setGridOverlay,
          imageWidth, imageHeight, canvasWidth, canvasHeight, zoom } = useCanvasStore();
  const { applyCrop, performUndo } = useCanvas();
  const { entries, currentIndex, canUndo } = useHistoryStore();

  // Crop overlay coordinates are in display pixel space (canvasPixels × zoom).
  // canvasWidth/Height reflect the current canvas after crop/rotate/resize;
  // fall back to imageWidth/Height on initial load.
  const currentW = canvasWidth  > 0 ? canvasWidth  : imageWidth;
  const currentH = canvasHeight > 0 ? canvasHeight : imageHeight;
  const displayW = currentW * zoom;
  const displayH = currentH * zoom;

  const SHAPE_OPTIONS: { value: CropShape; label: string }[] = [
    { value: 'rectangle', label: t.crop.shapes.rect    },
    { value: 'circle',    label: t.crop.shapes.circle  },
    { value: 'ellipse',   label: t.crop.shapes.ellipse },
    { value: 'rounded',   label: t.crop.shapes.rounded },
  ];

  const GRID_OPTIONS: { value: GridOverlay; label: string }[] = [
    { value: 'none',     label: t.crop.grids.none     },
    { value: 'thirds',   label: t.crop.grids.thirds   },
    { value: 'golden',   label: t.crop.grids.golden   },
    { value: 'center',   label: t.crop.grids.centre   },
    { value: 'diagonal', label: t.crop.grids.diagonal },
  ];

  // ── Shape change: non-rectangle shapes get a centered 80% crop box ───────────
  const handleShapeChange = (newShape: CropShape) => {
    if (newShape !== 'rectangle') {
      const newW = Math.round(displayW * 0.8);
      const newH = Math.round(displayH * 0.8);
      const newX = Math.round((displayW - newW) / 2);
      const newY = Math.round((displayH - newH) / 2);
      setCrop({ shape: newShape, ratio: 'free', width: newW, height: newH, x: newX, y: newY });
    } else {
      setCrop({ shape: newShape });
    }
  };

  // ── Ratio change: resize the crop box to match, clamped to display size ───────
  const handleRatioChange = (newRatio: AspectRatio) => {
    const ar = ratioToNumber(newRatio);
    if (!ar) {
      setCrop({ ratio: newRatio });
      return;
    }
    const currentW = crop.width > 0 ? crop.width : displayW;
    let newW = currentW;
    let newH = Math.round(newW / ar);
    if (newH > displayH) {
      newH = displayH;
      newW = Math.round(newH * ar);
    }
    const newX = Math.round((displayW - newW) / 2);
    const newY = Math.round((displayH - newH) / 2);
    setCrop({ ratio: newRatio, x: newX, y: newY, width: newW, height: newH });
  };

  const handleApplyCrop = () => {
    if (crop.width < 1 || crop.height < 1) return;
    // crop coords are in canvas pixel space
    applyCrop({
      x:      Math.round(crop.x),
      y:      Math.round(crop.y),
      width:  Math.round(crop.width),
      height: Math.round(crop.height),
    });
  };

  const handleResetCrop = () => {
    // If the last committed operation was a crop, undo it to restore the pixels
    const lastEntry = entries[currentIndex];
    if (canUndo && lastEntry?.label === 'Crop') {
      performUndo();
    }
    // Always clear the selection so CropOverlay reinitialises to the current canvas
    resetCrop();
  };

  return (
    <div className="ultra-panel">
      <div className="ultra-panel__header">
        <h3 className="ultra-panel__title">{t.crop.title}</h3>
      </div>

      {/* Aspect Ratio — only for Rectangle */}
      {crop.shape === 'rectangle' && (
        <div className="ultra-panel__section">
          <label className="ultra-section-label">{t.crop.aspectRatio}</label>
          <div className="ultra-ratio-grid">
            {RATIO_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                className={`ultra-ratio-btn ${crop.ratio === opt.value ? 'ultra-ratio-btn--active' : ''}`}
                onClick={() => handleRatioChange(opt.value)}
                aria-pressed={crop.ratio === opt.value}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Shape */}
      <div className="ultra-panel__section">
        <label className="ultra-section-label">{t.crop.shape}</label>
        <div className="ultra-shape-selector">
          {SHAPE_OPTIONS.map((opt) => (
            <button
              key={opt.value}
              className={`ultra-shape-btn ${crop.shape === opt.value ? 'ultra-shape-btn--active' : ''}`}
              onClick={() => handleShapeChange(opt.value)}
              aria-pressed={crop.shape === opt.value}
            >
              {opt.label}
            </button>
          ))}
        </div>
      </div>

      {/* Grid Overlay */}
      <div className="ultra-panel__section">
        <label className="ultra-section-label">{t.crop.gridOverlay}</label>
        <select
          className="ultra-select"
          value={gridOverlay}
          onChange={(e) => setGridOverlay(e.target.value as GridOverlay)}
          aria-label="Grid overlay type"
        >
          {GRID_OPTIONS.map((opt) => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          ))}
        </select>
      </div>

      {/* Numeric inputs — in image pixel space */}
      <div className="ultra-panel__section">
        <label className="ultra-section-label">{t.crop.positionSize}</label>
        <div className="ultra-numeric-grid">
          {([
            { key: 'x' as const,      label: 'X', max: displayW },
            { key: 'y' as const,      label: 'Y', max: displayH },
            { key: 'width' as const,  label: 'W', max: displayW },
            { key: 'height' as const, label: 'H', max: displayH },
          ] as const).map(({ key, label, max }) => (
            <div key={key} className="ultra-numeric-field">
              <label className="ultra-numeric-label">{label}</label>
              <input
                type="number"
                className="ultra-input"
                value={Math.round(crop[key])}
                min={0}
                max={max}
                onChange={(e) => {
                  const val = Number(e.target.value);
                  const ar = ratioToNumber(crop.ratio);
                  if (ar && (key === 'width' || key === 'height')) {
                    if (key === 'width')  setCrop({ width: val, height: Math.round(val / ar) });
                    if (key === 'height') setCrop({ height: val, width: Math.round(val * ar) });
                  } else {
                    setCrop({ [key]: val });
                  }
                }}
                aria-label={`Crop ${label}`}
              />
            </div>
          ))}
        </div>
      </div>

      {/* Actions */}
      <div className="ultra-panel__actions">
        <button className="ultra-btn ultra-btn--secondary" onClick={handleResetCrop}>
          {t.common.reset}
        </button>
        <button
          className="ultra-btn ultra-btn--primary"
          onClick={handleApplyCrop}
          disabled={crop.width < 1 || crop.height < 1}
        >
          {t.crop.applyCrop}
        </button>
      </div>
    </div>
  );
};
