"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import AdminLayout from "@/components/admin/AdminLayout";
import {
  PlusIcon,
  EditIcon,
  TrashIcon,
  EyeIcon,
  ExternalLinkIcon,
  SearchIcon,
  FilterIcon,
  FolderIcon,
} from "@/components/Icons";

interface Project {
  id: number;
  title: string;
  slug: string;
  shortDescription: string | null;
  categoryId: number | null;
  categoryName?: string;
  categoryColor?: string;
  tags: string | null;
  liveUrl: string | null;
  featured: boolean | null;
  published: boolean | null;
  views: number | null;
  createdAt: string;
}

interface Category {
  id: number;
  name: string;
  slug: string;
  color: string | null;
}

export default function ProjectsPage() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");

  const fetchData = useCallback(async () => {
    try {
      const [projectsRes, categoriesRes] = await Promise.all([
        fetch("/api/admin/projects"),
        fetch("/api/admin/categories"),
      ]);
      
      if (projectsRes.ok && categoriesRes.ok) {
        const projectsData = await projectsRes.json();
        const categoriesData = await categoriesRes.json();
        setProjects(projectsData.projects);
        setCategories(categoriesData.categories);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleDelete = async (id: number) => {
    if (!confirm("Are you sure you want to delete this project?")) return;

    try {
      const res = await fetch(`/api/admin/projects/${id}`, { method: "DELETE" });
      if (res.ok) {
        setProjects(projects.filter((p) => p.id !== id));
      }
    } catch (e) {
      console.error(e);
    }
  };

  const togglePublish = async (project: Project) => {
    try {
      const res = await fetch(`/api/admin/projects/${project.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...project, published: !project.published }),
      });
      if (res.ok) {
        setProjects(
          projects.map((p) =>
            p.id === project.id ? { ...p, published: !p.published } : p
          )
        );
      }
    } catch (e) {
      console.error(e);
    }
  };

  const filtered = projects.filter((p) => {
    const matchesSearch =
      !searchQuery ||
      p.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.tags?.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory =
      !categoryFilter || p.categoryId?.toString() === categoryFilter;
    const matchesStatus =
      !statusFilter ||
      (statusFilter === "published" && p.published) ||
      (statusFilter === "draft" && !p.published) ||
      (statusFilter === "featured" && p.featured);
    return matchesSearch && matchesCategory && matchesStatus;
  });

  const getCategoryInfo = (categoryId: number | null) => {
    if (!categoryId) return { name: "Uncategorized", color: "#64748b" };
    const cat = categories.find((c) => c.id === categoryId);
    return { name: cat?.name || "Unknown", color: cat?.color || "#64748b" };
  };

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-text-primary">Projects</h1>
            <p className="text-text-muted mt-1">
              Manage your portfolio projects
            </p>
          </div>
          <Link
            href="/admin/projects/new"
            className="inline-flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-primary to-primary-light text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/25 transition-all text-sm"
          >
            <PlusIcon size={16} />
            Add Project
          </Link>
        </div>

        {/* Filters */}
        <div className="glass rounded-xl p-4">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* Search */}
            <div className="flex-1 relative">
              <SearchIcon
                size={16}
                className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted"
              />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search projects..."
                className="w-full pl-10 pr-4 py-2.5 bg-surface border border-border rounded-xl text-sm"
              />
            </div>

            {/* Category filter */}
            <div className="relative">
              <FilterIcon
                size={16}
                className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted"
              />
              <select
                value={categoryFilter}
                onChange={(e) => setCategoryFilter(e.target.value)}
                className="pl-10 pr-8 py-2.5 bg-surface border border-border rounded-xl text-sm appearance-none cursor-pointer min-w-[150px]"
              >
                <option value="">All Categories</option>
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name}
                  </option>
                ))}
              </select>
            </div>

            {/* Status filter */}
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-4 py-2.5 bg-surface border border-border rounded-xl text-sm appearance-none cursor-pointer min-w-[130px]"
            >
              <option value="">All Status</option>
              <option value="published">Published</option>
              <option value="draft">Draft</option>
              <option value="featured">Featured</option>
            </select>
          </div>
        </div>

        {/* Projects table */}
        <div className="glass rounded-xl overflow-hidden">
          {loading ? (
            <div className="p-12 text-center">
              <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full mx-auto" />
            </div>
          ) : filtered.length === 0 ? (
            <div className="p-12 text-center">
              <FolderIcon size={48} className="text-text-muted mx-auto mb-4" />
              <p className="text-text-muted text-lg mb-2">No projects found</p>
              <Link
                href="/admin/projects/new"
                className="inline-flex items-center gap-1 text-primary-light hover:text-accent text-sm"
              >
                <PlusIcon size={14} /> Create your first project
              </Link>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-surface-elevated border-b border-border">
                    <th className="text-left py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Project
                    </th>
                    <th className="text-left py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Category
                    </th>
                    <th className="text-left py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Status
                    </th>
                    <th className="text-left py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Views
                    </th>
                    <th className="text-left py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Date
                    </th>
                    <th className="text-right py-4 px-6 text-xs font-semibold text-text-muted uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filtered.map((project) => {
                    const catInfo = getCategoryInfo(project.categoryId);
                    return (
                      <tr
                        key={project.id}
                        className="hover:bg-surface-hover transition-colors"
                      >
                        <td className="py-4 px-6">
                          <div className="flex items-center gap-3">
                            <div
                              className="w-10 h-10 rounded-lg flex items-center justify-center text-lg"
                              style={{ backgroundColor: `${catInfo.color}20` }}
                            >
                              📁
                            </div>
                            <div>
                              <p className="font-semibold text-text-primary">
                                {project.title}
                              </p>
                              <p className="text-xs text-text-muted truncate max-w-[250px]">
                                {project.shortDescription || "No description"}
                              </p>
                            </div>
                          </div>
                        </td>
                        <td className="py-4 px-6">
                          <span
                            className="inline-block px-2.5 py-1 text-xs font-medium rounded-lg"
                            style={{
                              backgroundColor: `${catInfo.color}20`,
                              color: catInfo.color,
                            }}
                          >
                            {catInfo.name}
                          </span>
                        </td>
                        <td className="py-4 px-6">
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => togglePublish(project)}
                              className={`px-2.5 py-1 text-xs font-medium rounded-lg transition-colors ${
                                project.published
                                  ? "bg-success/10 text-success hover:bg-success/20"
                                  : "bg-warning/10 text-warning hover:bg-warning/20"
                              }`}
                            >
                              {project.published ? "Published" : "Draft"}
                            </button>
                            {project.featured && (
                              <span className="px-2 py-0.5 text-[10px] bg-amber-500/10 text-amber-400 rounded">
                                ⭐ Featured
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="py-4 px-6">
                          <span className="text-text-secondary">
                            {project.views?.toLocaleString() || 0}
                          </span>
                        </td>
                        <td className="py-4 px-6">
                          <span className="text-text-muted text-sm">
                            {new Date(project.createdAt).toLocaleDateString()}
                          </span>
                        </td>
                        <td className="py-4 px-6">
                          <div className="flex items-center justify-end gap-1">
                            <Link
                              href={`/projects/${project.slug}`}
                              target="_blank"
                              className="p-2 text-text-muted hover:text-accent rounded-lg hover:bg-white/5 transition-colors"
                              title="View"
                            >
                              <EyeIcon size={16} />
                            </Link>
                            {project.liveUrl && (
                              <a
                                href={project.liveUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="p-2 text-text-muted hover:text-primary-light rounded-lg hover:bg-white/5 transition-colors"
                                title="Live site"
                              >
                                <ExternalLinkIcon size={16} />
                              </a>
                            )}
                            <Link
                              href={`/admin/projects/${project.id}`}
                              className="p-2 text-text-muted hover:text-primary-light rounded-lg hover:bg-white/5 transition-colors"
                              title="Edit"
                            >
                              <EditIcon size={16} />
                            </Link>
                            <button
                              onClick={() => handleDelete(project.id)}
                              className="p-2 text-text-muted hover:text-danger rounded-lg hover:bg-danger/10 transition-colors"
                              title="Delete"
                            >
                              <TrashIcon size={16} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Stats footer */}
        <div className="flex items-center justify-between text-sm text-text-muted">
          <p>
            Showing {filtered.length} of {projects.length} projects
          </p>
          <div className="flex items-center gap-4">
            <span>
              📊 Total views: {projects.reduce((sum, p) => sum + (p.views || 0), 0).toLocaleString()}
            </span>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}
