"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import AdminLayout from "@/components/admin/AdminLayout";
import {
  ArrowRightIcon,
  CheckIcon,
  SpinnerIcon,
  EyeIcon,
  ExternalLinkIcon,
  MaximizeIcon,
  XIcon,
} from "@/components/Icons";

interface Category {
  id: number;
  name: string;
  slug: string;
}

interface FormData {
  title: string;
  shortDescription: string;
  description: string;
  categoryId: string;
  tags: string;
  liveUrl: string;
  githubUrl: string;
  embedUrl: string;
  featured: boolean;
  published: boolean;
}

export default function ProjectFormPage() {
  const router = useRouter();
  const params = useParams();
  const isNew = params.id === "new";
  const projectId = isNew ? null : Number(params.id);

  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [formData, setFormData] = useState<FormData>({
    title: "",
    shortDescription: "",
    description: "",
    categoryId: "",
    tags: "",
    liveUrl: "",
    githubUrl: "",
    embedUrl: "",
    featured: false,
    published: true,
  });

  const fetchData = useCallback(async () => {
    try {
      const catRes = await fetch("/api/admin/categories");
      if (catRes.ok) {
        const catData = await catRes.json();
        setCategories(catData.categories);
      }

      if (projectId) {
        const projRes = await fetch(`/api/admin/projects/${projectId}`);
        if (projRes.ok) {
          const projData = await projRes.json();
          const p = projData.project;
          setFormData({
            title: p.title || "",
            shortDescription: p.shortDescription || "",
            description: p.description || "",
            categoryId: p.categoryId?.toString() || "",
            tags: p.tags || "",
            liveUrl: p.liveUrl || "",
            githubUrl: p.githubUrl || "",
            embedUrl: p.embedUrl || "",
            featured: p.featured || false,
            published: p.published !== false,
          });
        }
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [projectId]);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const url = projectId
        ? `/api/admin/projects/${projectId}`
        : "/api/admin/projects";
      const method = projectId ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        router.push("/admin/projects");
      } else {
        const data = await res.json();
        alert(data.error || "Failed to save project");
      }
    } catch (e) {
      console.error(e);
      alert("Failed to save project");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center py-20">
          <SpinnerIcon size={40} className="text-primary" />
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="max-w-5xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2 text-sm text-text-muted mb-2">
              <Link href="/admin/projects" className="hover:text-text-primary">
                Projects
              </Link>
              <span>/</span>
              <span className="text-text-primary">
                {isNew ? "New Project" : "Edit Project"}
              </span>
            </div>
            <h1 className="text-2xl font-bold text-text-primary">
              {isNew ? "Create New Project" : "Edit Project"}
            </h1>
          </div>
          <div className="flex items-center gap-3">
            {formData.liveUrl && (
              <button
                type="button"
                onClick={() => setShowPreview(true)}
                className="px-4 py-2 border border-border text-text-secondary rounded-xl hover:bg-white/5 transition-colors flex items-center gap-2 text-sm"
              >
                <EyeIcon size={16} />
                Preview
              </button>
            )}
            <Link
              href="/admin/projects"
              className="px-4 py-2 border border-border text-text-secondary rounded-xl hover:bg-white/5 transition-colors text-sm"
            >
              Cancel
            </Link>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid lg:grid-cols-3 gap-6">
            {/* Main content */}
            <div className="lg:col-span-2 space-y-6">
              <div className="glass rounded-xl p-6 space-y-5">
                <h2 className="font-semibold text-text-primary border-b border-border pb-3">
                  Basic Information
                </h2>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Project Title *
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.title}
                    onChange={(e) =>
                      setFormData({ ...formData, title: e.target.value })
                    }
                    placeholder="My Awesome Project"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Short Description
                  </label>
                  <input
                    type="text"
                    value={formData.shortDescription}
                    onChange={(e) =>
                      setFormData({ ...formData, shortDescription: e.target.value })
                    }
                    placeholder="A brief summary of the project"
                    maxLength={500}
                    className="w-full"
                  />
                  <p className="text-xs text-text-muted mt-1">
                    {formData.shortDescription.length}/500 characters
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Full Description
                  </label>
                  <textarea
                    rows={10}
                    value={formData.description}
                    onChange={(e) =>
                      setFormData({ ...formData, description: e.target.value })
                    }
                    placeholder="Detailed project description. Supports markdown..."
                    className="w-full font-mono text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Tags (comma-separated)
                  </label>
                  <input
                    type="text"
                    value={formData.tags}
                    onChange={(e) =>
                      setFormData({ ...formData, tags: e.target.value })
                    }
                    placeholder="PHP, Laravel, API, FinTech"
                    className="w-full"
                  />
                </div>
              </div>

              <div className="glass rounded-xl p-6 space-y-5">
                <h2 className="font-semibold text-text-primary border-b border-border pb-3">
                  Links & Embeds
                </h2>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Live URL
                  </label>
                  <input
                    type="url"
                    value={formData.liveUrl}
                    onChange={(e) =>
                      setFormData({ ...formData, liveUrl: e.target.value })
                    }
                    placeholder="https://project.example.com"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    GitHub URL
                  </label>
                  <input
                    type="url"
                    value={formData.githubUrl}
                    onChange={(e) =>
                      setFormData({ ...formData, githubUrl: e.target.value })
                    }
                    placeholder="https://github.com/username/repo"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Embed URL (for live preview)
                  </label>
                  <input
                    type="url"
                    value={formData.embedUrl}
                    onChange={(e) =>
                      setFormData({ ...formData, embedUrl: e.target.value })
                    }
                    placeholder="URL to embed in iframe preview"
                    className="w-full"
                  />
                  <p className="text-xs text-text-muted mt-1">
                    If different from Live URL, or for YouTube/Vimeo embeds
                  </p>
                </div>
              </div>
            </div>

            {/* Sidebar */}
            <div className="space-y-6">
              <div className="glass rounded-xl p-6 space-y-5">
                <h2 className="font-semibold text-text-primary border-b border-border pb-3">
                  Publish Settings
                </h2>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Category
                  </label>
                  <select
                    value={formData.categoryId}
                    onChange={(e) =>
                      setFormData({ ...formData, categoryId: e.target.value })
                    }
                    className="w-full"
                  >
                    <option value="">Select category</option>
                    {categories.map((cat) => (
                      <option key={cat.id} value={cat.id}>
                        {cat.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-3">
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.published}
                      onChange={(e) =>
                        setFormData({ ...formData, published: e.target.checked })
                      }
                      className="w-4 h-4 rounded"
                    />
                    <div>
                      <span className="text-sm font-medium text-text-primary">
                        Published
                      </span>
                      <p className="text-xs text-text-muted">
                        Visible on your portfolio
                      </p>
                    </div>
                  </label>

                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={formData.featured}
                      onChange={(e) =>
                        setFormData({ ...formData, featured: e.target.checked })
                      }
                      className="w-4 h-4 rounded"
                    />
                    <div>
                      <span className="text-sm font-medium text-text-primary">
                        Featured
                      </span>
                      <p className="text-xs text-text-muted">
                        Highlight on homepage
                      </p>
                    </div>
                  </label>
                </div>
              </div>

              {/* Preview card */}
              {formData.liveUrl && (
                <div className="glass rounded-xl p-6">
                  <h2 className="font-semibold text-text-primary mb-4">
                    Quick Preview
                  </h2>
                  <div className="rounded-lg border border-border overflow-hidden bg-surface h-40 flex items-center justify-center">
                    <button
                      type="button"
                      onClick={() => setShowPreview(true)}
                      className="flex flex-col items-center gap-2 text-text-muted hover:text-text-primary transition-colors"
                    >
                      <MaximizeIcon size={24} />
                      <span className="text-sm">Open Preview</span>
                    </button>
                  </div>
                </div>
              )}

              {/* Actions */}
              <div className="glass rounded-xl p-6 space-y-3">
                <button
                  type="submit"
                  disabled={saving}
                  className="w-full 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 disabled:opacity-50"
                >
                  {saving ? (
                    <>
                      <SpinnerIcon size={18} />
                      Saving...
                    </>
                  ) : (
                    <>
                      <CheckIcon size={18} />
                      {isNew ? "Create Project" : "Update Project"}
                    </>
                  )}
                </button>

                <Link
                  href="/admin/projects"
                  className="block w-full py-3 text-center border border-border text-text-secondary rounded-xl hover:bg-white/5 transition-colors text-sm"
                >
                  Cancel
                </Link>
              </div>
            </div>
          </div>
        </form>

        {/* Preview modal */}
        {showPreview && (
          <div
            className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
            onClick={(e) => {
              if (e.target === e.currentTarget) setShowPreview(false);
            }}
          >
            <div className="bg-surface-card rounded-2xl w-full max-w-6xl h-[85vh] flex flex-col overflow-hidden border border-border">
              <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>
                  <span className="text-sm text-text-muted truncate max-w-md">
                    {formData.embedUrl || formData.liveUrl}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <a
                    href={formData.liveUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-2 text-text-muted hover:text-text-primary transition-colors"
                  >
                    <ExternalLinkIcon size={16} />
                  </a>
                  <button
                    onClick={() => setShowPreview(false)}
                    className="p-2 text-text-muted hover:text-text-primary transition-colors"
                  >
                    <XIcon size={16} />
                  </button>
                </div>
              </div>
              <div className="flex-1 bg-white">
                <iframe
                  src={formData.embedUrl || formData.liveUrl}
                  className="w-full h-full border-none"
                  sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
                  title="Project preview"
                />
              </div>
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
