"use client";

import { useState } from "react";
import { createProjectAction, updateProjectAction } from "./actions";
import { useRouter } from "@/i18n/routing";
import { Loader2, Upload, PlusCircle, ArrowLeft, Save, X, ImagePlus } from "lucide-react";

export function ProjectForm({ initialData, projectId }: { initialData?: any; projectId?: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Multiple images state
  // existingPreviews: URLs of images already saved (for edit mode)
  // newPreviews: blob URLs of newly selected files
  const [existingPreviews, setExistingPreviews] = useState<string[]>(
    initialData?.imageUrls && initialData.imageUrls.length > 0
      ? initialData.imageUrls
      : initialData?.imageUrl
      ? [initialData.imageUrl]
      : []
  );
  const [newFiles, setNewFiles] = useState<File[]>([]);
  const [newPreviews, setNewPreviews] = useState<string[]>([]);

  function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files || []);
    const previews = files.map((f) => URL.createObjectURL(f));
    setNewFiles((prev) => [...prev, ...files]);
    setNewPreviews((prev) => [...prev, ...previews]);
    // Reset input so same files can be re-selected
    e.target.value = "";
  }

  function removeExistingImage(idx: number) {
    setExistingPreviews((prev) => prev.filter((_, i) => i !== idx));
  }

  function removeNewImage(idx: number) {
    URL.revokeObjectURL(newPreviews[idx]);
    setNewFiles((prev) => prev.filter((_, i) => i !== idx));
    setNewPreviews((prev) => prev.filter((_, i) => i !== idx));
  }

  const allPreviews = [...existingPreviews, ...newPreviews];

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const formData = new FormData(e.currentTarget);

      // Remove the placeholder file inputs, we'll add manually
      formData.delete("images");

      // Append existing image URLs that were kept
      existingPreviews.forEach((url) => formData.append("existingImages", url));

      // Append new file objects
      newFiles.forEach((file) => formData.append("images", file));

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

      const response = await fetch(url, { method, body: formData });
      const result = await response.json();

      if (!response.ok || !result.success) {
        setError(result.message || "An error occurred");
        setLoading(false);
      } else {
        setLoading(false);
        router.refresh();
        router.push("/admin/dashboard/projects");
      }
    } catch (err) {
      setError("An unexpected error occurred during submission.");
      setLoading(false);
    }
  }

  return (
    <div className="max-w-3xl mx-auto p-6 lg:p-10 rounded-3xl bg-card border border-border overflow-hidden relative shadow-sm">
      <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-accent to-purple-500" />
      
      <div className="mb-8 flex items-center gap-4">
        <button 
          type="button" 
          onClick={() => router.back()}
          className="p-2 rounded-full hover:bg-muted text-muted-foreground transition-colors"
        >
          <ArrowLeft size={20} />
        </button>
        <div>
          <h1 className="text-2xl font-bold tracking-tight">
            {projectId ? "Edit Project" : "Create New Project"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {projectId ? "Update your portfolio case study" : "Add a new case study to your portfolio"}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {error && (
          <div className="p-4 rounded-xl bg-error/10 border border-error/20 text-error text-sm font-medium">
            {error}
          </div>
        )}

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Project Title</label>
            <input 
              name="title" 
              required 
              defaultValue={initialData?.title}
              placeholder="Core Banking API"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">URL Slug</label>
            <input 
              name="slug" 
              required 
              defaultValue={initialData?.slug}
              placeholder="core-banking-api"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
          </div>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Category</label>
          <select 
            name="category"
            required
            defaultValue={initialData?.category || "Enterprise Backend"}
            className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono cursor-pointer"
          >
            <option value="Enterprise Backend">Enterprise Backend</option>
            <option value="Frontend Development">Frontend Development</option>
            <option value="Mobile Development">Mobile Development</option>
          </select>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Description</label>
          <textarea 
            name="description" 
            required 
            defaultValue={initialData?.description}
            rows={4}
            placeholder="High-performance API Gateway handling 500K+ daily transactions..."
            className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono resize-y"
          />
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Live URL (Optional)</label>
            <input 
              name="liveUrl" 
              type="url"
              defaultValue={initialData?.liveUrl || ""}
              placeholder="https://example.com"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">Repository URL (Optional)</label>
            <input 
              name="repoUrl" 
              type="url"
              defaultValue={initialData?.repoUrl || ""}
              placeholder="https://github.com/..."
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
          </div>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Tech Stack</label>
            <input
              name="techStack"
              defaultValue={initialData?.techStack?.join(", ") || ""}
              placeholder="Java, Spring Boot, PostgreSQL, Docker"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
            <p className="text-xs text-muted-foreground">Pisahkan setiap teknologi dengan koma</p>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">Tahun Pengerjaan</label>
            <input
              name="year"
              type="number"
              min="2000"
              max="2099"
              defaultValue={initialData?.year || new Date().getFullYear()}
              placeholder={new Date().getFullYear().toString()}
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
            />
          </div>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Target & Pencapaian</label>
          <textarea
            name="highlights"
            defaultValue={initialData?.highlights?.join(", ") || ""}
            rows={3}
            placeholder="Reduce API latency 40%, Handle 10K daily users, 99.9% uptime"
            className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
          />
          <p className="text-xs text-muted-foreground">Pisahkan setiap pencapaian dengan koma</p>
        </div>

        {/* --- Multiple Image Upload --- */}
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <label className="text-sm font-semibold">Project Images</label>
            <span className="text-xs text-muted-foreground">{allPreviews.length} gambar dipilih</span>
          </div>

          {/* Grid preview */}
          {allPreviews.length > 0 && (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {/* Existing images */}
              {existingPreviews.map((url, idx) => (
                <div key={`existing-${idx}`} className="relative group rounded-xl overflow-hidden border border-border aspect-video bg-muted/20">
                  <img src={url} alt={`Image ${idx + 1}`} className="w-full h-full object-cover" />
                  {idx === 0 && (
                    <span className="absolute top-1.5 left-1.5 text-[10px] font-bold bg-accent text-accent-foreground px-2 py-0.5 rounded-full">
                      Cover
                    </span>
                  )}
                  <button
                    type="button"
                    onClick={() => removeExistingImage(idx)}
                    className="absolute top-1.5 right-1.5 p-1 bg-black/60 hover:bg-red-600 rounded-full text-white opacity-0 group-hover:opacity-100 transition-all"
                  >
                    <X size={12} />
                  </button>
                </div>
              ))}
              {/* New images */}
              {newPreviews.map((url, idx) => (
                <div key={`new-${idx}`} className="relative group rounded-xl overflow-hidden border border-accent/30 aspect-video bg-muted/20">
                  <img src={url} alt={`New ${idx + 1}`} className="w-full h-full object-cover" />
                  {existingPreviews.length === 0 && idx === 0 && (
                    <span className="absolute top-1.5 left-1.5 text-[10px] font-bold bg-accent text-accent-foreground px-2 py-0.5 rounded-full">
                      Cover
                    </span>
                  )}
                  <span className="absolute bottom-1.5 left-1.5 text-[10px] bg-black/50 text-white px-1.5 py-0.5 rounded">
                    Baru
                  </span>
                  <button
                    type="button"
                    onClick={() => removeNewImage(idx)}
                    className="absolute top-1.5 right-1.5 p-1 bg-black/60 hover:bg-red-600 rounded-full text-white opacity-0 group-hover:opacity-100 transition-all"
                  >
                    <X size={12} />
                  </button>
                </div>
              ))}
            </div>
          )}

          {/* Upload trigger */}
          <label className="flex items-center justify-center gap-3 w-full py-4 rounded-xl border-2 border-dashed border-border hover:border-accent/50 bg-muted/10 hover:bg-muted/30 cursor-pointer transition-colors">
            <ImagePlus size={20} className="text-muted-foreground" />
            <div className="text-center">
              <span className="text-sm font-medium text-muted-foreground">
                {allPreviews.length > 0 ? "Tambah lebih banyak gambar" : "Klik untuk upload gambar"}
              </span>
              <p className="text-xs text-muted-foreground/60 mt-0.5">PNG, JPG, WEBP · Bisa pilih banyak sekaligus</p>
            </div>
            <input 
              type="file" 
              name="images"
              accept="image/*" 
              multiple
              className="hidden" 
              onChange={handleFileSelect}
            />
          </label>
        </div>

        <div className="flex items-center gap-3 pt-2">
          <input 
            type="checkbox" 
            name="isPublished" 
            id="isPublished"
            className="w-5 h-5 rounded border-border text-accent focus:ring-accent/50"
            defaultChecked={initialData ? initialData.isPublished : true}
          />
          <label htmlFor="isPublished" className="text-sm font-medium cursor-pointer">
            Publish immediately (visible to visitors)
          </label>
        </div>

        <div className="pt-6 border-t border-border/50 flex justify-end">
          <button
            type="submit"
            disabled={loading}
            className="flex items-center gap-2 px-8 py-3 rounded-xl bg-foreground text-background font-semibold text-sm hover:opacity-90 transition-all disabled:opacity-50 disabled:scale-100 hover:scale-[1.02] shadow-md"
          >
            {loading ? (
              <Loader2 size={18} className="animate-spin" />
            ) : projectId ? (
              <>
                <Save size={18} />
                Update Project
              </>
            ) : (
              <>
                <PlusCircle size={18} />
                Save Project
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
