'use client';

import { LayoutTemplate } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

interface Template {
  id: string;
  title: string;
  category?: string;
  description?: string;
}

const Page = () => {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchTemplates = async () => {
      try {
        const res = await fetch('/api/v1/templates');
        if (!res.ok) throw new Error('Failed to fetch');
        const data = await res.json();
        setTemplates(data.items ?? []);
      } catch {
        toast.error('Failed to load templates');
      } finally {
        setLoading(false);
      }
    };
    fetchTemplates();
  }, []);

  return (
    <div className="flex flex-col pt-10 pb-28 lg:pb-8 px-4 max-w-4xl mx-auto w-full">
      <div className="flex items-center gap-3 border-b border-light-200/20 dark:border-dark-200/20 pb-6">
        <LayoutTemplate size={40} className="text-[#7C3AED]" />
        <h1 className="text-4xl font-normal">Space Templates</h1>
      </div>

      <p className="mt-4 text-black/60 dark:text-white/60">
        Ready-made Spaces for finance, marketing, product, and travel.
      </p>

      {loading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-6">
          {[1, 2, 3, 4].map((i) => (
            <div
              key={i}
              className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-4 animate-pulse h-24"
            />
          ))}
        </div>
      ) : templates.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-6">
          {templates.map((t) => (
            <Link
              key={t.id}
              href={`/?template=${t.id}`}
              className="rounded-2xl bg-light-secondary dark:bg-dark-secondary p-5 shadow-sm border border-light-200/20 dark:border-dark-200/20 block hover:border-[#7C3AED]/30 transition-colors"
            >
              <h2 className="font-medium text-lg">{t.title}</h2>
              {t.description && (
                <p className="text-sm text-black/60 dark:text-white/60 mt-1">{t.description}</p>
              )}
              {t.category && (
                <span className="inline-block mt-2 text-xs px-2 py-0.5 rounded bg-light-200 dark:bg-dark-200">
                  {t.category}
                </span>
              )}
            </Link>
          ))}
        </div>
      ) : (
        <div className="mt-6 p-6 rounded-2xl bg-light-secondary dark:bg-dark-secondary text-center text-black/60 dark:text-white/60">
          <p>No templates available. Enable projects-svc in deploy.config.yaml</p>
        </div>
      )}

      <div className="mt-8">
        <Link
          href="/spaces"
          className="text-sm text-[#7C3AED] hover:underline"
        >
          ← Back to Spaces
        </Link>
      </div>
    </div>
  );
};

export default Page;
