"use client";

import { useState } from "react";
import {
  ExternalLinkIcon,
  GithubIcon,
  EyeIcon,
  MaximizeIcon,
  XIcon,
} from "./Icons";

interface Category {
  id: number;
  name: string;
  slug: string;
  icon: string | null;
  color: 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;
}

// Portfolio categories mapping
const portfolioTypes = [
  { id: "all", name: "All Work", icon: "🎯", slugs: [] },
  { id: "website", name: "Websites", icon: "🌐", slugs: ["website"] },
  { id: "webapp", name: "Web Apps", icon: "📱", slugs: ["webapp"] },
  { id: "coding", name: "Coding Projects", icon: "💻", slugs: ["webapp", "automation", "ai"] },
  { id: "design", name: "Graphic Design", icon: "🎨", slugs: ["design"] },
  { id: "video", name: "Video Portfolio", icon: "🎬", slugs: ["video"] },
  { id: "music", name: "Music & Audio", icon: "🎵", slugs: ["music"] },
  { id: "content", name: "Content Writing", icon: "✍️", slugs: ["content"] },
  { id: "ai", name: "AI Projects", icon: "🤖", slugs: ["ai"] },
];

const getCategoryEmoji = (slug: string | undefined) => {
  const emojiMap: Record<string, string> = {
    website: "🌐",
    webapp: "📱",
    design: "🎨",
    ai: "🤖",
    mobile: "📲",
    automation: "⚡",
    video: "🎬",
    music: "🎵",
    content: "✍️",
  };
  return emojiMap[slug || ""] || "💻";
};

const getCategoryGradient = (slug: string | undefined) => {
  const gradients: Record<string, string> = {
    website: "from-blue-500 to-indigo-600",
    webapp: "from-purple-500 to-pink-600",
    design: "from-pink-500 to-rose-600",
    ai: "from-cyan-500 to-blue-600",
    mobile: "from-green-500 to-emerald-600",
    automation: "from-amber-500 to-orange-600",
    video: "from-red-500 to-rose-600",
    music: "from-violet-500 to-purple-600",
    content: "from-teal-500 to-cyan-600",
  };
  return gradients[slug || ""] || "from-gray-500 to-gray-700";
};

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

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

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

  const filtered = activeFilter === "all"
    ? projects
    : projects.filter((p) => {
        const slug = getCategorySlug(p.categoryId);
        const type = portfolioTypes.find((t) => t.id === activeFilter);
        return type?.slugs.includes(slug || "") || false;
      });

  return (
    <section id="portfolio" 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">
            My <span className="gradient-text">Creative Work</span>
          </h2>
          <p className="text-text-muted max-w-2xl mx-auto text-lg">
            A showcase of my work across web development, graphic design, video production, music, and more
          </p>
        </div>

        {/* Category Tabs */}
        <div className="flex flex-wrap justify-center gap-2 mb-12">
          {portfolioTypes.map((type) => (
            <button
              key={type.id}
              onClick={() => setActiveFilter(type.id)}
              className={`px-4 py-2.5 rounded-xl text-sm font-medium transition-all flex items-center gap-2 ${
                activeFilter === type.id
                  ? "bg-gradient-to-r from-primary to-accent text-white shadow-lg shadow-primary/25"
                  : "bg-surface-card text-text-secondary hover:text-text-primary border border-border hover:border-primary/30"
              }`}
            >
              <span>{type.icon}</span>
              <span className="hidden sm:inline">{type.name}</span>
            </button>
          ))}
        </div>

        {/* Projects Grid */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {filtered.map((project) => {
            const catSlug = getCategorySlug(project.categoryId);
            const catGradient = getCategoryGradient(catSlug);
            const catEmoji = getCategoryEmoji(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 */}
                <div className="relative h-48 overflow-hidden bg-surface-elevated">
                  <div className={`absolute inset-0 bg-gradient-to-br ${catGradient} opacity-20`} />
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="text-center">
                      <div className="text-5xl mb-2">{catEmoji}</div>
                      <span className="text-sm text-text-muted">
                        {getCategoryName(project.categoryId)}
                      </span>
                    </div>
                  </div>

                  {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-11 h-11 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={20} />
                      </button>
                    )}
                    {project.liveUrl && (
                      <a
                        href={project.liveUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="w-11 h-11 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                      >
                        <ExternalLinkIcon size={20} />
                      </a>
                    )}
                    {project.githubUrl && (
                      <a
                        href={project.githubUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="w-11 h-11 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                      >
                        <GithubIcon size={20} />
                      </a>
                    )}
                  </div>
                </div>

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

                  <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, 3).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 > 3 && (
                      <span className="px-2 py-0.5 text-xs text-text-muted">
                        +{tags.length - 3}
                      </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 in this category yet.
            </p>
          </div>
        )}

        {/* View All CTA */}
        <div className="text-center mt-12">
          <a
            href="#contact"
            className="inline-flex items-center gap-2 px-8 py-4 bg-gradient-to-r from-primary to-primary-light text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/25 transition-all btn-shimmer"
          >
            🚀 Let&apos;s Work Together
          </a>
        </div>
      </div>

      {/* Embed Modal */}
      {embedProject && (
        <div
          className="fixed inset-0 z-[100] bg-black/80 backdrop-blur-sm flex items-center justify-center p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) setEmbedProject(null);
          }}
        >
          <div
            className={`bg-surface-card rounded-2xl overflow-hidden shadow-2xl border border-border ${
              embedFullscreen
                ? "fixed inset-4 z-[101]"
                : "w-full max-w-5xl 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</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
