'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { TemplateDetail } from '@/components/marketplace/TemplateDetail';
import { Loader2 } from 'lucide-react';

export default function TemplateDetailPage() {
  const { templateId } = useParams<{ templateId: string }>();
  const [template, setTemplate] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!templateId) return;

    async function fetchTemplate() {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`/api/marketplace/${templateId}`);
        if (!res.ok) {
          throw new Error(res.status === 404 ? 'Template not found' : 'Failed to load template');
        }
        const json = await res.json();
        setTemplate(json.data || json);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load template');
      } finally {
        setLoading(false);
      }
    }

    fetchTemplate();
  }, [templateId]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <Loader2 className="h-8 w-8 text-indigo-500 animate-spin" />
      </div>
    );
  }

  if (error || !template) {
    return (
      <div className="min-h-screen bg-gray-950 flex flex-col items-center justify-center text-center p-6">
        <h2 className="text-xl font-semibold text-white mb-2">
          {error || 'Template not found'}
        </h2>
        <p className="text-gray-400 text-sm mb-6">
          The template you&apos;re looking for might have been removed or doesn&apos;t exist.
        </p>
        <a
          href="/marketplace"
          className="px-5 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium
                     hover:bg-indigo-500 transition-colors"
        >
          Back to Marketplace
        </a>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-950 p-6 lg:p-8">
      <TemplateDetail template={template} />
    </div>
  );
}
