"use client";

import { useState } from "react";
import {
  ExternalLinkIcon,
  GithubIcon,
  EyeIcon,
  MaximizeIcon,
  XIcon,
  FilterIcon,
} from "./Icons";
import { getCategoryColor } from "@/lib/utils";

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

interface Project {
  id: number;
  title: string;
  slug: string;
  description: string | null;
  shortDescription: string | null;
  categoryId: number | null;
  tags: string | null;
  liveUrl: string | null;
  githubUrl: string | null;
  embedUrl: string | null;
  previewImage: string | null;
  featured: boolean | null;
  published: boolean | null;
  sortOrder: number | null;
}

export default function ProjectsSection({
  projects,
  categories,
}: {
  projects: Project[];
  categories: Category[];
}) {
  const [activeFilter, setActiveFilter] = useState("all");
  const [embedProject, setEmbedProject] = useState<Project | null>(null);
  const [embedFullscreen, setEmbedFullscreen] = useState(false);

  const filtered =
    activeFilter === "all"
      ? projects
      : projects.filter((p) => {
          const cat = categories.find((c) => c.id === p.categoryId);
          return cat?.slug === activeFilter;
        });

  const getCategoryName = (categoryId: number | null) => {
    if (!categoryId) return "Other";
    return categories.find((c) => c.id === categoryId)?.name || "Other";
  };

  const getCategorySlug = (categoryId: number | null) => {
    if (!categoryId) return "other";
    return categories.find((c) => c.id === categoryId)?.slug || "other";
  };

  return (
    <section id="projects" className="py-24 relative overflow-hidden">
      <div className="absolute inset-0 hero-gradient opacity-30" />

      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-12">
          <span className="inline-block px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-accent bg-accent/10 rounded-full mb-4">
            Portfolio
          </span>
          <h2 className="text-4xl sm:text-5xl font-bold text-text-primary mb-4">
            Featured <span className="gradient-text">Projects</span>
          </h2>
          <p className="text-text-muted max-w-2xl mx-auto text-lg">
            A curated selection of my best work across web development, AI, and
            automation
          </p>
        </div>

        {/* Filter Tabs */}
        <div className="flex flex-wrap items-center justify-center gap-2 mb-12">
          <button
            onClick={() => setActiveFilter("all")}
            className={`px-5 py-2.5 rounded-xl text-sm font-medium transition-all ${
              activeFilter === "all"
                ? "bg-primary text-white shadow-lg shadow-primary/25"
                : "bg-surface-card text-text-secondary hover:text-text-primary hover:bg-surface-hover border border-border"
            }`}
          >
            <span className="flex items-center gap-1.5">
              <FilterIcon size={14} />
              All
            </span>
          </button>
          {categories.map((cat) => (
            <button
              key={cat.id}
              onClick={() => setActiveFilter(cat.slug)}
              className={`px-5 py-2.5 rounded-xl text-sm font-medium transition-all ${
                activeFilter === cat.slug
                  ? "bg-primary text-white shadow-lg shadow-primary/25"
                  : "bg-surface-card text-text-secondary hover:text-text-primary hover:bg-surface-hover border border-border"
              }`}
            >
              {cat.name}
            </button>
          ))}
        </div>

        {/* Project Grid */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {filtered.map((project) => {
            const catSlug = getCategorySlug(project.categoryId);
            const catColor = getCategoryColor(catSlug);
            const tags = project.tags?.split(",").map((t) => t.trim()) || [];

            return (
              <div
                key={project.id}
                className="group glass rounded-2xl overflow-hidden card-hover"
              >
                {/* Preview Image / Placeholder */}
                <div className="relative h-48 overflow-hidden bg-surface-elevated">
                  <div
                    className={`absolute inset-0 bg-gradient-to-br ${catColor} opacity-20`}
                  />
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="text-center">
                      <div className="text-4xl mb-2">
                        {catSlug === "webapp"
                          ? "📱"
                          : catSlug === "website"
                          ? "🌐"
                          : catSlug === "design"
                          ? "🎨"
                          : catSlug === "ai"
                          ? "🤖"
                          : catSlug === "mobile"
                          ? "📲"
                          : catSlug === "automation"
                          ? "⚡"
                          : "💻"}
                      </div>
                      <span className="text-sm text-text-muted">
                        {getCategoryName(project.categoryId)}
                      </span>
                    </div>
                  </div>

                  {/* Featured badge */}
                  {project.featured && (
                    <div className="absolute top-3 left-3 px-2.5 py-1 rounded-lg bg-amber-500/90 text-white text-xs font-semibold">
                      ⭐ Featured
                    </div>
                  )}

                  {/* Hover overlay */}
                  <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
                    {(project.liveUrl || project.embedUrl) && (
                      <button
                        onClick={() => setEmbedProject(project)}
                        className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                        title="Live Preview"
                      >
                        <EyeIcon size={18} />
                      </button>
                    )}
                    {project.liveUrl && (
                      <a
                        href={project.liveUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                        title="Open in new tab"
                      >
                        <ExternalLinkIcon size={18} />
                      </a>
                    )}
                    {project.githubUrl && (
                      <a
                        href={project.githubUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                        title="GitHub"
                      >
                        <GithubIcon size={18} />
                      </a>
                    )}
                  </div>
                </div>

                {/* Content */}
                <div className="p-6">
                  <div className="flex items-center gap-2 mb-3">
                    <span
                      className={`px-2.5 py-0.5 text-xs font-semibold rounded-full bg-gradient-to-r ${catColor} text-white`}
                    >
                      {getCategoryName(project.categoryId)}
                    </span>
                  </div>

                  <h3 className="text-lg font-bold text-text-primary mb-2 group-hover:text-primary-light transition-colors">
                    {project.title}
                  </h3>

                  <p className="text-sm text-text-secondary leading-relaxed mb-4 line-clamp-2">
                    {project.shortDescription || project.description}
                  </p>

                  {/* Tags */}
                  <div className="flex flex-wrap gap-1.5">
                    {tags.slice(0, 4).map((tag) => (
                      <span
                        key={tag}
                        className="px-2 py-0.5 text-xs rounded-md bg-surface-elevated text-text-muted border border-border"
                      >
                        {tag}
                      </span>
                    ))}
                    {tags.length > 4 && (
                      <span className="px-2 py-0.5 text-xs rounded-md text-text-muted">
                        +{tags.length - 4}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {filtered.length === 0 && (
          <div className="text-center py-16">
            <div className="text-5xl mb-4">🔍</div>
            <p className="text-text-muted text-lg">
              No projects found in this category yet.
            </p>
          </div>
        )}
      </div>

      {/* Embed Modal */}
      {embedProject && (
        <div
          className="modal-backdrop"
          onClick={(e) => {
            if (e.target === e.currentTarget) setEmbedProject(null);
          }}
        >
          <div
            className={`modal-content bg-surface-card rounded-2xl overflow-hidden shadow-2xl border border-border ${
              embedFullscreen
                ? "fixed inset-4 z-[101]"
                : "w-full max-w-5xl mx-4 max-h-[85vh]"
            }`}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-4 border-b border-border">
              <div className="flex items-center gap-3">
                <div className="flex gap-1.5">
                  <span className="w-3 h-3 rounded-full bg-red-500" />
                  <span className="w-3 h-3 rounded-full bg-yellow-500" />
                  <span className="w-3 h-3 rounded-full bg-green-500" />
                </div>
                <h3 className="font-semibold text-text-primary text-sm">
                  {embedProject.title}
                </h3>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setEmbedFullscreen(!embedFullscreen)}
                  className="p-2 text-text-muted hover:text-text-primary transition-colors"
                >
                  <MaximizeIcon size={16} />
                </button>
                {embedProject.liveUrl && (
                  <a
                    href={embedProject.liveUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-2 text-text-muted hover:text-text-primary transition-colors"
                  >
                    <ExternalLinkIcon size={16} />
                  </a>
                )}
                <button
                  onClick={() => {
                    setEmbedProject(null);
                    setEmbedFullscreen(false);
                  }}
                  className="p-2 text-text-muted hover:text-text-primary transition-colors"
                >
                  <XIcon size={16} />
                </button>
              </div>
            </div>

            {/* URL Bar */}
            <div className="px-4 py-2 border-b border-border bg-surface-elevated">
              <div className="flex items-center gap-2 px-3 py-1.5 bg-surface rounded-lg text-sm text-text-muted">
                <span className="text-success">🔒</span>
                <span className="truncate">
                  {embedProject.embedUrl || embedProject.liveUrl || "Preview"}
                </span>
              </div>
            </div>

            {/* Iframe */}
            <div
              className={`bg-white ${
                embedFullscreen ? "h-[calc(100%-7rem)]" : "h-[60vh]"
              }`}
            >
              {embedProject.embedUrl || embedProject.liveUrl ? (
                <iframe
                  src={embedProject.embedUrl || embedProject.liveUrl || ""}
                  className="w-full h-full border-none"
                  sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
                  title={embedProject.title}
                  loading="lazy"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-surface-elevated">
                  <div className="text-center">
                    <div className="text-5xl mb-4">🖼️</div>
                    <p className="text-text-muted">
                      No preview available for this project
                    </p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
