'use client';

import { useState } from 'react';
import { Sparkles, X, Loader2, Download, Film, Image as ImageIcon } from 'lucide-react';
import { EFFECT_TEMPLATES, EffectTemplate } from '@/lib/effect-templates';
import { callFunction } from '@/lib/firebase';

interface EffectPickerProps {
  eventId: string;
  photoId: string;
  photoUrl: string;
  onClose: () => void;
}

interface EffectResult {
  url: string;
  kind: 'image' | 'video';
  templateId: string;
}

export default function EffectPicker({ eventId, photoId, photoUrl, onClose }: EffectPickerProps) {
  const [selected, setSelected] = useState<EffectTemplate | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<EffectResult | null>(null);

  const apply = async (template: EffectTemplate) => {
    setSelected(template);
    setLoading(true);
    setError(null);
    setResult(null);
    try {
      const res = (await callFunction('applyPhotoEffect')({
        eventId,
        photoId,
        templateId: template.id,
      })) as { data: EffectResult };
      setResult(res.data);
    } catch (e: any) {
      setError(e?.message || 'Effect generation failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-[110] bg-black/95 flex items-center justify-center p-4"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-label="Photo Effects"
    >
      <div
        className="max-w-3xl w-full max-h-[90vh] overflow-y-auto bg-zinc-950 rounded-2xl border border-zinc-800 p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-5">
          <div className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-amber-300" />
            <h2 className="text-lg font-semibold text-white">AI Photo Effects</h2>
          </div>
          <button
            onClick={onClose}
            className="h-8 w-8 rounded-full bg-zinc-800 hover:bg-zinc-700 flex items-center justify-center"
            aria-label="Close effects"
          >
            <X className="h-4 w-4 text-white" />
          </button>
        </div>

        {!result && !loading && (
          <>
            <p className="text-xs text-zinc-400 mb-4">
              Pick a template — Higgsfield AI will transform your photo. Image effects ~25s, video effects ~90s.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {EFFECT_TEMPLATES.map((t) => (
                <button
                  key={t.id}
                  onClick={() => apply(t)}
                  className="group relative text-start rounded-xl border border-zinc-800 hover:border-amber-400/60 bg-zinc-900 hover:bg-zinc-800 p-3 transition-all"
                  aria-label={`Apply ${t.name} effect`}
                >
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-2xl">{t.icon}</span>
                    {t.kind === 'video' ? (
                      <Film className="h-3 w-3 text-amber-300" />
                    ) : (
                      <ImageIcon className="h-3 w-3 text-zinc-500" />
                    )}
                  </div>
                  <p className="text-sm font-medium text-white">{t.name}</p>
                  <p className="text-[10px] text-zinc-500 mt-1 line-clamp-2">{t.description}</p>
                  <p className="text-[10px] text-zinc-600 mt-1">~{t.etaSeconds}s</p>
                </button>
              ))}
            </div>
          </>
        )}

        {loading && selected && (
          <div className="flex flex-col items-center justify-center py-12">
            <Loader2 className="h-10 w-10 text-amber-300 animate-spin mb-3" />
            <p className="text-sm font-medium text-white">Applying {selected.name}…</p>
            <p className="text-xs text-zinc-500 mt-1">This can take ~{selected.etaSeconds}s. Please keep this tab open.</p>
            <div className="mt-6 max-w-xs">
              <img src={photoUrl} alt="" className="w-full rounded-xl opacity-50" />
            </div>
          </div>
        )}

        {error && !loading && (
          <div className="rounded-xl bg-red-500/10 border border-red-500/30 p-4 text-sm text-red-300">
            <p className="font-medium">Effect failed</p>
            <p className="text-xs mt-1 opacity-90">{error}</p>
            <button
              onClick={() => { setError(null); setSelected(null); }}
              className="mt-3 h-8 px-3 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-xs"
            >
              Try another effect
            </button>
          </div>
        )}

        {result && !loading && (
          <div className="space-y-4">
            <p className="text-sm text-emerald-300 font-medium">✨ Effect ready!</p>
            <div className="rounded-xl overflow-hidden bg-black">
              {result.kind === 'video' ? (
                <video src={result.url} controls autoPlay loop className="w-full" />
              ) : (
                <img src={result.url} alt="Effect result" className="w-full" />
              )}
            </div>
            <div className="flex gap-2">
              <a
                href={result.url}
                target="_blank"
                rel="noopener noreferrer"
                download
                className="flex-1 h-10 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center justify-center gap-2 hover:bg-amber-200"
              >
                <Download className="h-4 w-4" /> Download
              </a>
              <button
                onClick={() => { setResult(null); setSelected(null); }}
                className="flex-1 h-10 rounded-lg border border-zinc-700 text-white text-sm hover:bg-zinc-800"
              >
                Try another effect
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
