"use client";

import { useState } from "react";
import { useUser } from "@clerk/nextjs";

const MAX_FILES = 3;
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];

interface ImageData {
  key: string;
  url: string;
  order: number;
}

interface ImageUploaderProps {
  images: { key: string; order: number; url?: string }[];
  onImagesChange: (images: { key: string; order: number; url?: string }[]) => void;
}

export default function ImageUploader({ images, onImagesChange }: ImageUploaderProps) {
  const { user } = useUser();
  const [uploading, setUploading] = useState(false);
  const [previews, setPreviews] = useState<ImageData[]>([]);
  const [error, setError] = useState("");

  const currentCount = images.length;

  const handleFiles = async (files: FileList) => {
    const remaining = MAX_FILES - currentCount;
    if (remaining <= 0) return;

    const validFiles = Array.from(files)
      .filter((f) => ALLOWED_TYPES.includes(f.type))
      .filter((f) => f.size <= MAX_FILE_SIZE)
      .slice(0, remaining);

    if (validFiles.length === 0) {
      setError("Невалиден тип на датотека или големина. Дозволени: JPEG, PNG, WebP, GIF до 5MB.");
      return;
    }

    setError("");
    setUploading(true);

    try {
      const newImages = [...images];
      const newPreviews = [...previews];

      for (const file of validFiles) {
        const formData = new FormData();
        formData.append("file", file);

        const res = await fetch("/api/upload", {
          method: "POST",
          body: formData,
        });

        if (!res.ok) {
          const data = await res.json();
          throw new Error(data.error || "Не успеа качувањето");
        }

        const { key, url } = await res.json();
        const order = newImages.length + 1;
        newImages.push({ key, order, url });
        newPreviews.push({ key, url, order });
      }

      onImagesChange(newImages);
      setPreviews(newPreviews);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Не успеа качувањето");
    } finally {
      setUploading(false);
    }
  };

  const remaining = MAX_FILES - currentCount;

  return (
    <div className="space-y-4">
      <div>
        <p className="text-sm text-stone-600">
          Качете до {MAX_FILES} фотографии (макс. {MAX_FILE_SIZE / 1024 / 1024}MB секоја, JPEG/PNG/WebP/GIF)
        </p>

        <label className="mt-3 flex cursor-pointer items-center justify-center rounded-lg border-2 border-dashed border-stone-300 bg-stone-50 px-6 py-8 transition-colors hover:border-primary hover:bg-stone-100">
          <div className="text-center">
            <p className="text-sm font-medium text-stone-700">
              {uploading ? "Качување..." : "Кликнете за качување или влечете и пуштете"}
            </p>
            {remaining > 0 && !uploading && (
              <p className="mt-1 text-xs text-stone-400">Преостануваат {remaining} места</p>
            )}
          </div>
          <input
            type="file"
            accept={ALLOWED_TYPES.join(",")}
            multiple
            className="hidden"
            disabled={uploading || currentCount >= MAX_FILES}
            onChange={(e) => e.target.files && handleFiles(e.target.files)}
            onDragOver={(e) => e.preventDefault()}
            onDrop={(e) => {
              e.preventDefault();
              e.dataTransfer.files && handleFiles(e.dataTransfer.files);
            }}
          />
        </label>
      </div>

      {error && (
        <p className="text-sm text-red-600">{error}</p>
      )}

      {previews.length > 0 && (
        <div className="grid grid-cols-3 gap-3">
          {previews.map((preview) => (
            <div key={preview.key} className="group relative overflow-hidden rounded-lg border border-stone-200">
              <img src={preview.url} alt="" className="h-32 w-full object-cover" />
              <button
                onClick={() => {
                  const idx = images.findIndex((img) => img.key === preview.key);
                  if (idx === -1) return;
                  const updated = images.filter((img) => img.key !== preview.key).map((img, i) => ({ ...img, order: i + 1 }));
                  onImagesChange(updated);
                  setPreviews(previews.filter((p) => p.key !== preview.key));
                }}
                className="absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs text-white opacity-0 transition-opacity group-hover:opacity-100"
              >
                &times;
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}