"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { landingPageContentApi } from "@/lib/api";
import Layout from "@/app/components/Layout";

interface LandingPageContent {
  id: number;
  type: "carousel" | "section" | "content";
  title: string | null;
  content: string | null;
  imageUrl: string | null;
  videoUrl: string | null;
  linkUrl: string | null;
  linkText: string | null;
  order: number;
  isActive: boolean;
  metadata: any;
  createdAt: string;
}

export default function LandingPageManagement() {
  const [contents, setContents] = useState<LandingPageContent[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<"all" | "carousel" | "section" | "content">("all");

  useEffect(() => {
    fetchContents();
  }, [filter]);

  const fetchContents = async () => {
    try {
      setLoading(true);
      const response = await landingPageContentApi.getAll({
        type: filter !== "all" ? filter : undefined,
      });
      if (response.success) {
        setContents(response.data);
      }
    } catch (error) {
      console.error("Error fetching content:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Are you sure you want to delete this content?")) return;
    try {
      await landingPageContentApi.delete(id);
      fetchContents();
    } catch (error) {
      console.error("Error deleting content:", error);
      alert("Failed to delete content");
    }
  };

  const toggleActive = async (id: number, currentStatus: boolean) => {
    try {
      await landingPageContentApi.update(id, { isActive: !currentStatus });
      fetchContents();
    } catch (error) {
      console.error("Error updating content:", error);
      alert("Failed to update content");
    }
  };

  return (
    <Layout>
      <div className="p-6">
        <div className="max-w-7xl mx-auto">
          <div className="flex justify-between items-center mb-6">
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Landing Page Management</h1>
            <Link
              href="/landing-page/new"
              className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Add New Content
            </Link>
          </div>

        <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div className="flex gap-2">
            <button
              onClick={() => setFilter("all")}
              className={`px-4 py-2 rounded-lg transition-colors ${
                filter === "all"
                  ? "bg-blue-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              All
            </button>
            <button
              onClick={() => setFilter("carousel")}
              className={`px-4 py-2 rounded-lg transition-colors ${
                filter === "carousel"
                  ? "bg-blue-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Carousel
            </button>
            <button
              onClick={() => setFilter("section")}
              className={`px-4 py-2 rounded-lg transition-colors ${
                filter === "section"
                  ? "bg-blue-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Section
            </button>
            <button
              onClick={() => setFilter("content")}
              className={`px-4 py-2 rounded-lg transition-colors ${
                filter === "content"
                  ? "bg-blue-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Content
            </button>
          </div>
        </div>

        {loading ? (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p className="mt-2 text-gray-600">Loading content...</p>
          </div>
        ) : contents.length === 0 ? (
          <div className="bg-white rounded-lg shadow-sm p-12 text-center">
            <p className="text-gray-600">No content found</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {contents.map((item) => (
              <div
                key={item.id}
                className="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow"
              >
                {item.imageUrl && (
                  <div className="h-48 bg-gray-200 overflow-hidden">
                    <img
                      src={item.imageUrl}
                      alt={item.title || "Content"}
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
                <div className="p-4">
                  <div className="flex items-start justify-between mb-2">
                    <span
                      className={`px-2 py-1 text-xs font-semibold rounded ${
                        item.type === "carousel"
                          ? "bg-purple-100 text-purple-800"
                          : item.type === "section"
                          ? "bg-blue-100 text-blue-800"
                          : "bg-green-100 text-green-800"
                      }`}
                    >
                      {item.type}
                    </span>
                    <span
                      className={`px-2 py-1 text-xs font-semibold rounded ${
                        item.isActive
                          ? "bg-green-100 text-green-800"
                          : "bg-red-100 text-red-800"
                      }`}
                    >
                      {item.isActive ? "Active" : "Inactive"}
                    </span>
                  </div>
                  <h3 className="font-semibold text-gray-900 mb-2">
                    {item.title || "Untitled"}
                  </h3>
                  {item.content && (
                    <p className="text-sm text-gray-600 mb-2 line-clamp-2">
                      {item.content}
                    </p>
                  )}
                  <div className="text-xs text-gray-500 mb-4">
                    Order: {item.order}
                  </div>
                  <div className="flex gap-2">
                    <Link
                      href={`/landing-page/${item.id}/edit`}
                      className="flex-1 text-center px-3 py-2 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors"
                    >
                      Edit
                    </Link>
                    <button
                      onClick={() => toggleActive(item.id, item.isActive)}
                      className={`px-3 py-2 text-sm rounded transition-colors ${
                        item.isActive
                          ? "bg-yellow-100 text-yellow-800 hover:bg-yellow-200"
                          : "bg-green-100 text-green-800 hover:bg-green-200"
                      }`}
                    >
                      {item.isActive ? "Deactivate" : "Activate"}
                    </button>
                    <button
                      onClick={() => handleDelete(item.id)}
                      className="px-3 py-2 bg-red-100 text-red-800 text-sm rounded hover:bg-red-200 transition-colors"
                    >
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
        </div>
      </div>
    </Layout>
  );
}

