/**
 * FormOption
 * Renders one selectable trait option with its preview media and optional
 * detail dialog launcher for larger images and descriptions.
 */
import React, { useState } from 'react';
import { Button } from "@/components/ui/button";
import { Dialog, DialogTrigger } from "@/components/ui/dialog";
import { Maximize2, ImageOff } from "lucide-react";
import { useDragControls } from "framer-motion";
import OptionDetailDialog from './OptionDetailDialog';
import { useLanguage } from '../../context/LanguageContext';
import { toAbsoluteApiUrl } from '../../utils/api';

export default function FormOption({ opt, isSelected, onChange, znakLabel, znakPopis, viewMode, disabled = false }) {
  const { l, t } = useLanguage();
  const dragControls = useDragControls();
  const [isOpen, setIsOpen] = useState(false);

  const getDisplayImages = () => {
    let images = [];
    if (viewMode === 'drawing') {
      images = [...(opt.factoryDrawings || []), ...(opt.userDrawings || []).map(img => img.path)];
    } else {
      images = [...(opt.factoryImages || []), ...(opt.userImages || []).map(img => img.path)];
    }
    
    return images.map(path => toAbsoluteApiUrl(path));
  };

  const activeImages = getDisplayImages();
  const hasImages = activeImages.length > 0;
  const handleSelect = () => {
    if (disabled) return;
    onChange(opt.label_cs);
  };

  return (
    <div className="group relative flex h-full w-full justify-center">
      <div
        onClick={handleSelect}
        aria-disabled={disabled}
        className={`flex h-full w-full flex-col overflow-hidden rounded-xl border-2 bg-white transition-all duration-200 ${
          disabled
            ? 'cursor-not-allowed opacity-60 border-slate-100'
            : isSelected
              ? "cursor-pointer border-blue-600 ring-2 ring-blue-100"
              : "cursor-pointer border-slate-100 hover:border-slate-300"
        }`}
      >
        <div
          className="relative flex w-full items-center justify-center bg-slate-50 p-1.5"
          style={{ height: 'clamp(136px, 11vw, 220px)' }}
        >
          {hasImages ? (
            <>
              <img
                src={activeImages[0]}
                className={`w-full h-full object-contain transition-transform ${disabled ? '' : 'group-hover:scale-105'}`}
                alt="preview"
              />

              {activeImages.length > 1 && (
                <div className="absolute bottom-1 right-1 bg-black/60 text-white text-[8px] px-1.5 py-0.5 rounded-md font-bold backdrop-blur-sm">
                  1 / {activeImages.length}
                </div>
              )}
            </>
          ) : (
            <div className="flex h-full w-full items-center justify-center rounded-lg border border-dashed border-slate-200 bg-white/60">
              <div className="flex flex-col items-center gap-1 text-slate-300">
                <ImageOff className="h-8 w-8" />
                <span className="text-[9px] font-bold uppercase tracking-wide">{t('noImage')}</span>
              </div>
            </div>
          )}
        </div>
        <div className={`flex min-h-[36px] items-center justify-center border-t px-1 py-1 text-center ${isSelected ? "bg-blue-600 text-white" : "bg-slate-50 text-slate-500"}`}>
          <span className="text-[9px] font-bold uppercase leading-tight">{l(opt, 'label')}</span>
        </div>
      </div>

      {(hasImages || znakPopis) && (
        <Dialog onOpenChange={setIsOpen}>
          <DialogTrigger asChild>
            <Button size="icon" className="absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 bg-white/90 shadow-md border z-20">
              <Maximize2 className="h-3 w-3 text-slate-600" />
            </Button>
          </DialogTrigger>
          <OptionDetailDialog
            isOpen={isOpen}
            dragControls={dragControls}
            znakLabel={znakLabel}
            opt={opt}
            imgArray={activeImages}
            znakPopis={znakPopis}
          />
        </Dialog>
      )}
    </div>
  );
}