'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import {
  ArrowLeft,
  Eye,
  EyeOff,
  FileCode,
  Loader2,
  RefreshCw,
  LayoutTemplate,
} from 'lucide-react';
import { toast } from 'sonner';
import { Switch } from '@/components/ui/switch';

interface LayoutItem {
  db_id: number;
  layout_id: string;
  layout_name: string;
  is_enabled: boolean;
  thumbnail_path: string | null;
  has_code: boolean;
}

interface TemplateDetail {
  id: string;
  name: string;
  description?: string;
}

export default function TemplateDetailPage() {
  const params = useParams();
  const templateId = params.id as string;

  const [template, setTemplate] = useState<TemplateDetail | null>(null);
  const [layouts, setLayouts] = useState<LayoutItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [togglingId, setTogglingId] = useState<number | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/ppt/template-management/get-templates/${templateId}`);
      if (!res.ok) throw new Error('Failed to load template');
      const data = await res.json();

      if (data.template) {
        setTemplate({
          id: String(data.template.id),
          name: data.template.name || 'Custom Template',
          description: data.template.description,
        });
      }

      const items: LayoutItem[] = (data.layouts || []).map((l: any) => ({
        db_id: l.db_id,
        layout_id: l.layout_id,
        layout_name: l.layout_name,
        is_enabled: l.is_enabled !== false,
        thumbnail_path: l.thumbnail_path || null,
        has_code: !!l.layout_code,
      }));
      setLayouts(items);
    } catch {
      toast.error('Failed to load template layouts');
    } finally {
      setLoading(false);
    }
  }, [templateId]);

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

  const handleToggle = async (layout: LayoutItem) => {
    if (!layout.db_id) {
      toast.error('Cannot toggle: layout ID missing');
      return;
    }
    setTogglingId(layout.db_id);
    try {
      const res = await fetch(
        `/api/v1/ppt/template-management/layouts/${layout.db_id}/toggle-enabled`,
        { method: 'PATCH' }
      );
      if (!res.ok) throw new Error('Toggle failed');
      const data = await res.json();
      setLayouts((prev) =>
        prev.map((l) =>
          l.db_id === layout.db_id ? { ...l, is_enabled: data.is_enabled } : l
        )
      );
      toast.success(data.is_enabled ? 'Layout enabled' : 'Layout disabled');
    } catch {
      toast.error('Failed to toggle layout');
    } finally {
      setTogglingId(null);
    }
  };

  const enabledCount = layouts.filter((l) => l.is_enabled).length;

  return (
    <div className="space-y-6 max-w-5xl">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/templates">
            <Button variant="ghost" size="sm">
              <ArrowLeft className="w-4 h-4 mr-1" />Back
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl font-semibold">
              {loading ? 'Loading...' : template?.name || 'Template Layouts'}
            </h1>
            {!loading && (
              <p className="text-sm text-gray-500">
                {enabledCount} of {layouts.length} layouts enabled
              </p>
            )}
          </div>
        </div>
        <Button variant="outline" size="sm" onClick={load} disabled={loading}>
          <RefreshCw className={`w-4 h-4 mr-1 ${loading ? 'animate-spin' : ''}`} />
          Refresh
        </Button>
      </div>

      {loading ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {[...Array(8)].map((_, i) => (
            <div key={i} className="aspect-video bg-gray-200 rounded-lg animate-pulse" />
          ))}
        </div>
      ) : layouts.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-gray-300 rounded-lg">
          <LayoutTemplate className="w-10 h-10 text-gray-400 mb-2" />
          <p className="text-gray-500">No layouts in this template.</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {layouts.map((layout) => (
            <div
              key={layout.layout_id}
              className={`bg-white rounded-lg border overflow-hidden transition-opacity ${
                layout.is_enabled ? '' : 'opacity-50'
              }`}
            >
              {/* Thumbnail — served via admin screenshot API */}
              {layout.thumbnail_path ? (
                <div className="aspect-video bg-gray-100 overflow-hidden">
                  <img
                    src={`/api/v1/admin/master-decks/${templateId}/screenshot/${layout.thumbnail_path.split('/').pop()}`}
                    alt={layout.layout_name}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = 'none';
                    }}
                  />
                </div>
              ) : (
                <div className="aspect-video bg-gray-50 flex items-center justify-center">
                  <FileCode className="w-8 h-8 text-gray-300" />
                </div>
              )}
              {/* Info + toggle */}
              <div className="p-2">
                <p className="text-xs font-medium truncate mb-1">{layout.layout_name}</p>
                <div className="flex items-center justify-between">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded ${
                    layout.has_code
                      ? 'bg-green-50 text-green-600'
                      : 'bg-orange-50 text-orange-600'
                  }`}>
                    {layout.has_code ? 'Has layout' : 'No layout'}
                  </span>
                  <div className="flex items-center gap-1">
                    {togglingId === layout.db_id ? (
                      <Loader2 className="w-3.5 h-3.5 animate-spin text-gray-400" />
                    ) : (
                      <Switch
                        checked={layout.is_enabled}
                        onCheckedChange={() => handleToggle(layout)}
                        className="scale-75"
                      />
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
