"use client";

import { useState } from "react";
import { createExperienceAction, updateExperienceAction } from "./actions";
import { useRouter } from "@/i18n/routing";
import { Loader2, ArrowLeft, Save, PlusCircle } from "lucide-react";

type InitialData = {
  year?: string;
  title?: string;
  company?: string;
  description?: string;
  achievements?: string[];
  order?: number;
};

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

  const defaultAchievements = Array.isArray(initialData?.achievements)
    ? initialData!.achievements.join("\n")
    : "";

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

    const formData = new FormData(e.currentTarget);
    let result;
    if (experienceId) {
      result = await updateExperienceAction(experienceId, null, formData);
    } else {
      result = await createExperienceAction(null, formData);
    }

    if (!result.success) {
      setError(result.message || "An error occurred");
      setLoading(false);
    } else {
      router.push("/admin/dashboard/experience");
      router.refresh();
    }
  }

  return (
    <div className="max-w-2xl mx-auto p-6 lg:p-10 rounded-3xl bg-card border border-border shadow-sm relative overflow-hidden">
      <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-violet-500 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">
            {experienceId ? "Edit Experience" : "Add Work Experience"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {experienceId
              ? "Update your career timeline entry"
              : "Add a new entry to your career timeline"}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {error && (
          <div className="p-4 rounded-xl bg-red-500/10 border border-red-500/20 text-red-500 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">Year / Period</label>
            <input
              name="year"
              required
              defaultValue={initialData?.year}
              placeholder="e.g. 2024 — Present"
              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-violet-500/50 transition-all font-mono"
            />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-semibold">Display Order</label>
            <input
              name="order"
              type="number"
              defaultValue={initialData?.order ?? 0}
              placeholder="0 = first"
              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-violet-500/50 transition-all font-mono"
            />
          </div>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Job Title</label>
          <input
            name="title"
            required
            defaultValue={initialData?.title}
            placeholder="e.g. Senior Backend Developer"
            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-violet-500/50 transition-all"
          />
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Company</label>
          <input
            name="company"
            required
            defaultValue={initialData?.company}
            placeholder="e.g. PT Bank Mandiri"
            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-violet-500/50 transition-all"
          />
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Description</label>
          <textarea
            name="description"
            required
            defaultValue={initialData?.description}
            rows={3}
            placeholder="Describe your role and responsibilities..."
            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-violet-500/50 transition-all resize-y"
          />
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">
            Key Achievements{" "}
            <span className="text-muted-foreground font-normal text-xs">
              — satu baris per achievement
            </span>
          </label>
          <textarea
            name="achievements"
            defaultValue={defaultAchievements}
            rows={5}
            placeholder={
              "Architected event-driven system processing 500K+ transactions/day\nReduced API response time by 40% through caching optimization\nMentored team of 4 junior developers"
            }
            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-violet-500/50 transition-all font-mono resize-y"
          />
        </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 hover:scale-[1.02] shadow-md"
          >
            {loading ? (
              <Loader2 size={18} className="animate-spin" />
            ) : experienceId ? (
              <><Save size={18} /> Update</>
            ) : (
              <><PlusCircle size={18} /> Save Experience</>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
