'use client';

import React, { useRef } from 'react';
import { Camera, X } from 'lucide-react';
import { Photo, PhotoType } from '@/models/teltoinstall/_index';
import { useTranslation } from 'react-i18next';

interface Props {
  type: PhotoType;
  photos: Photo[];
  maxFiles: number;
  required?: boolean;
  label?: string;
  error?: string;
  onDrop: (files: File[], type: PhotoType) => void;
  onDelete: (index: number, type: PhotoType) => void;
}

export function PhotoDropzone({ type, photos, maxFiles, required, label, error, onDrop, onDelete }: Props) {
  const { t } = useTranslation();
  const inputRef = useRef<HTMLInputElement>(null);
  const typePhotos = photos.filter((p) => p.type === type);
  const canAdd = typePhotos.length < maxFiles;

  function handleFiles(files: FileList | null) {
    if (!files) return;
    const arr = Array.from(files).slice(0, maxFiles - typePhotos.length);
    if (arr.length > 0) onDrop(arr, type);
  }

  return (
    <div className="photo-upload-row flex-col items-start gap-2">
      <div className="flex items-center justify-between w-full">
        <span className="text-sm font-medium text-foreground">
          {label ?? `${t(`photos.${type}`)} (${maxFiles} max)`}
          {required && <span className="text-red-500"> *</span>}
        </span>
        {canAdd && (
          <button
            type="button"
            onClick={() => inputRef.current?.click()}
            className="px-3 py-1.5 bg-primary text-white text-sm font-medium rounded-lg flex items-center gap-1.5 active:scale-95 transition-transform shrink-0"
          >
            <Camera className="w-3.5 h-3.5" />
            {t('photos.add')}
          </button>
        )}
        <input
          ref={inputRef}
          type="file"
          accept="image/*"
          capture="environment"
          multiple
          className="hidden"
          onChange={(e) => handleFiles(e.target.files)}
          onClick={(e) => {
            (e.target as HTMLInputElement).value = '';
          }}
        />
      </div>

      {error && <p className="text-xs text-red-500 w-full">{error}</p>}

      {typePhotos.length > 0 && (
        <div className="flex flex-wrap gap-2 w-full">
          {typePhotos.map((photo, i) => {
            const src = photo.url ?? photo.path;
            const name = photo.filename?.split('/').pop() ?? 'Photo';
            return (
              <div key={i} className="relative">
                {src ? (
                  <img
                    src={src}
                    alt={name}
                    className="w-20 h-20 object-cover rounded-lg border border-border"
                  />
                ) : (
                  <div className="w-20 h-20 rounded-lg border border-border bg-muted flex items-center justify-center p-1">
                    <span className="text-[10px] text-center break-all text-muted-foreground">{name}</span>
                  </div>
                )}
                <button
                  type="button"
                  onClick={() => onDelete(i, type)}
                  className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center shadow-md"
                >
                  <X className="w-3 h-3" />
                </button>
                <span className="block text-xs text-primary mt-0.5 truncate max-w-[80px]">{name}</span>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
