"use client";

import { useState } from "react";
import {
  ArrowRightIcon,
  ExternalLinkIcon,
  GithubIcon,
  MaximizeIcon,
  XIcon,
  CodeIcon,
} from "@/components/Icons";
import { getCategoryColor } from "@/lib/utils";

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;
}

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

export default function ProjectDetailClient({
  project,
  category,
}: {
  project: Project;
  category: Category | null;
}) {
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [viewMode, setViewMode] = useState<"desktop" | "tablet" | "mobile">(
    "desktop"
  );
  const tags = project.tags?.split(",").map((t) => t.trim()) || [];
  const catColor = getCategoryColor(category?.slug || "");
  const embedSrc = project.embedUrl || project.liveUrl;

  const iframeWidths = {
    desktop: "100%",
    tablet: "768px",
    mobile: "375px",
  };

  return (
    <div className="min-h-screen bg-surface">
      {/* Header */}
      <header className="border-b border-border bg-surface-elevated/80 backdrop-blur-xl sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <a
              href="/"
              className="flex items-center gap-2 text-text-secondary hover:text-text-primary transition-colors"
            >
              <CodeIcon size={20} />
              <span className="font-bold">
                Samuel<span className="gradient-text">.dev</span>
              </span>
            </a>
            <span className="text-text-muted">/</span>
            <span className="text-text-primary font-semibold truncate max-w-[200px] sm:max-w-none">
              {project.title}
            </span>
          </div>

          <div className="flex items-center gap-2">
            {project.liveUrl && (
              <a
                href={project.liveUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="px-4 py-2 text-sm font-medium text-text-secondary hover:text-text-primary border border-border rounded-lg hover:bg-white/5 transition-all flex items-center gap-2"
              >
                <ExternalLinkIcon size={14} />
                <span className="hidden sm:inline">Live Site</span>
              </a>
            )}
            {project.githubUrl && (
              <a
                href={project.githubUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="px-4 py-2 text-sm font-medium text-text-secondary hover:text-text-primary border border-border rounded-lg hover:bg-white/5 transition-all flex items-center gap-2"
              >
                <GithubIcon size={14} />
                <span className="hidden sm:inline">GitHub</span>
              </a>
            )}
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="grid lg:grid-cols-3 gap-10">
          {/* Left: Project Info */}
          <div className="lg:col-span-1 space-y-6">
            {category && (
              <span
                className={`inline-block px-3 py-1 text-xs font-semibold rounded-full bg-gradient-to-r ${catColor} text-white`}
              >
                {category.name}
              </span>
            )}

            <h1 className="text-3xl sm:text-4xl font-bold text-text-primary">
              {project.title}
            </h1>

            {project.shortDescription && (
              <p className="text-lg text-text-secondary">
                {project.shortDescription}
              </p>
            )}

            {project.description && (
              <div className="prose prose-invert max-w-none">
                <p className="text-text-secondary leading-relaxed whitespace-pre-line">
                  {project.description}
                </p>
              </div>
            )}

            {/* Tags */}
            {tags.length > 0 && (
              <div className="flex flex-wrap gap-2">
                {tags.map((tag) => (
                  <span
                    key={tag}
                    className="px-3 py-1 text-xs rounded-lg bg-surface-elevated border border-border text-text-muted"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            )}

            {/* Actions */}
            <div className="pt-4 border-t border-border space-y-3">
              {project.liveUrl && (
                <a
                  href={project.liveUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-full px-5 py-3 bg-gradient-to-r from-primary to-primary-light text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/25 transition-all flex items-center justify-center gap-2 btn-shimmer"
                >
                  Visit Live Site
                  <ArrowRightIcon size={16} />
                </a>
              )}
              <a
                href="/#projects"
                className="w-full px-5 py-3 border border-border text-text-primary font-medium rounded-xl hover:bg-white/5 transition-all flex items-center justify-center gap-2"
              >
                ← Back to Projects
              </a>
            </div>
          </div>

          {/* Right: Embed Preview */}
          <div className="lg:col-span-2">
            {embedSrc ? (
              <div className="space-y-4">
                {/* Browser toolbar */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    {(["desktop", "tablet", "mobile"] as const).map((mode) => (
                      <button
                        key={mode}
                        onClick={() => setViewMode(mode)}
                        className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
                          viewMode === mode
                            ? "bg-primary text-white"
                            : "text-text-muted hover:text-text-primary bg-surface-elevated"
                        }`}
                      >
                        {mode === "desktop"
                          ? "🖥️ Desktop"
                          : mode === "tablet"
                          ? "📱 Tablet"
                          : "📲 Mobile"}
                      </button>
                    ))}
                  </div>
                  <button
                    onClick={() => setIsFullscreen(true)}
                    className="p-2 text-text-muted hover:text-text-primary transition-colors"
                  >
                    <MaximizeIcon size={18} />
                  </button>
                </div>

                {/* Embed frame */}
                <div className="embed-frame" style={{ height: "70vh" }}>
                  {/* Browser chrome */}
                  <div className="flex items-center gap-3 px-4 py-3 border-b border-border bg-surface-elevated">
                    <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>
                    <div className="flex-1 px-3 py-1 bg-surface rounded-lg text-xs text-text-muted truncate">
                      🔒 {embedSrc}
                    </div>
                  </div>

                  <div className="w-full h-[calc(100%-3rem)] flex justify-center bg-gray-100">
                    <iframe
                      src={embedSrc}
                      style={{ width: iframeWidths[viewMode], maxWidth: "100%" }}
                      className="h-full border-none transition-all duration-300"
                      sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
                      title={project.title}
                      loading="lazy"
                    />
                  </div>
                </div>
              </div>
            ) : (
              <div className="h-96 glass rounded-2xl flex items-center justify-center">
                <div className="text-center">
                  <div className="text-6xl mb-4">🖼️</div>
                  <p className="text-text-muted text-lg">
                    No live preview available
                  </p>
                  <p className="text-text-muted text-sm mt-2">
                    This project doesn&apos;t have an embeddable preview
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Fullscreen Modal */}
      {isFullscreen && embedSrc && (
        <div className="fixed inset-0 z-[100] bg-black">
          <div className="absolute top-4 right-4 z-10 flex items-center gap-2">
            <a
              href={embedSrc}
              target="_blank"
              rel="noopener noreferrer"
              className="p-2 bg-white/10 rounded-lg text-white hover:bg-white/20 transition-colors"
            >
              <ExternalLinkIcon size={18} />
            </a>
            <button
              onClick={() => setIsFullscreen(false)}
              className="p-2 bg-white/10 rounded-lg text-white hover:bg-white/20 transition-colors"
            >
              <XIcon size={18} />
            </button>
          </div>
          <iframe
            src={embedSrc}
            className="w-full h-full border-none"
            sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
            title={project.title}
          />
        </div>
      )}
    </div>
  );
}
