"use client";

import { useState } from "react";
import { createProjectAction, updateProjectAction } from "./actions";
import { useRouter } from "@/i18n/routing";
import { Loader2, Upload, PlusCircle, ArrowLeft, Save } 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);
  const [preview, setPreview] = useState<string | null>(initialData?.imageUrl || null);

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

    try {
      const formData = new FormData(e.currentTarget);
      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="space-y-2">
          <label className="text-sm font-semibold">Cover Image</label>
          <label className="flex flex-col items-center justify-center w-full h-40 rounded-xl border-2 border-dashed border-border hover:border-accent/50 bg-muted/10 hover:bg-muted/30 cursor-pointer transition-colors relative overflow-hidden">
            {preview ? (
              <img src={preview} alt="Preview" className="w-full h-full object-cover opacity-80" />
            ) : (
              <div className="flex flex-col items-center text-muted-foreground">
                <Upload size={24} className="mb-2" />
                <span className="text-sm font-medium">Click to upload image</span>
                <span className="text-xs mt-1 opacity-75">PNG, JPG, WEBP recommended</span>
              </div>
            )}
            <input 
              type="file" 
              name="image" 
              accept="image/*" 
              className="hidden" 
              onChange={(e) => {
                const file = e.target.files?.[0];
                if (file) setPreview(URL.createObjectURL(file));
              }}
            />
          </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>
  );
}
