"use client";

import { useEffect, useState, useRef } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { X, Upload, Film, Check } from "lucide-react";

interface MediaItem {
  id: string;
  slug: string;
  type: "image" | "video";
  mimeType: string;
  size: number;
  originalFilename: string;
  url: string;
}

interface MediaPickerModalProps {
  onSelect: (mediaId: string) => void;
  onClose: () => void;
  selectedId?: string | null;
}

export function MediaPickerModal({ onSelect, onClose, selectedId }: MediaPickerModalProps) {
  const [media, setMedia] = useState<MediaItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const loadMedia = async () => {
    try {
      const data = await api.getMediaList();
      setMedia(data.filter((m: MediaItem) => m.type === "image"));
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadMedia();
  }, []);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handleKey);
    return () => window.removeEventListener("keydown", handleKey);
  }, [onClose]);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    setError("");
    try {
      const result = await api.uploadMedia(file);
      await loadMedia();
      onSelect(result.id);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />
      <div className="relative bg-surface-container-low rounded-2xl w-full max-w-3xl max-h-[80vh] flex flex-col overflow-hidden">
        <div className="flex items-center justify-between p-5 border-b border-surface-container-highest">
          <h2 className="text-lg font-semibold text-on-surface">Select Image</h2>
          <div className="flex items-center gap-3">
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleUpload}
              className="hidden"
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
              className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-xs hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              <Upload size={14} />
              {uploading ? "Uploading..." : "Upload New"}
            </button>
            <button
              onClick={onClose}
              className="text-on-surface/50 hover:text-on-surface transition-colors"
            >
              <X size={20} />
            </button>
          </div>
        </div>

        {error && <p className="text-error text-sm px-5 pt-3">{error}</p>}

        <div className="flex-1 overflow-y-auto p-5">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <p className="text-on-surface/50 text-sm">Loading media...</p>
            </div>
          ) : media.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12">
              <p className="text-on-surface/50 text-sm">No images available.</p>
              <p className="text-on-surface/30 text-xs mt-1">Upload an image to get started.</p>
            </div>
          ) : (
            <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
              {media.map((item) => (
                <button
                  key={item.id}
                  onClick={() => onSelect(item.id)}
                  className={cn(
                    "relative aspect-square rounded-lg overflow-hidden border-2 transition-all hover:border-primary/60",
                    selectedId === item.id
                      ? "border-primary ring-2 ring-primary/30"
                      : "border-transparent"
                  )}
                >
                  {item.type === "image" ? (
                    <img
                      src={`/media/${item.id}?w=200`}
                      alt={item.originalFilename}
                      className="w-full h-full object-cover"
                      loading="lazy"
                    />
                  ) : (
                    <div className="w-full h-full bg-surface-container-highest flex items-center justify-center">
                      <Film size={24} className="text-on-surface/30" />
                    </div>
                  )}
                  {selectedId === item.id && (
                    <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
                      <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center">
                        <Check size={16} className="text-on-primary" />
                      </div>
                    </div>
                  )}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
