"use client";

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

type InitialData = {
  institution?: string;
  degree?: string;
  fieldOfStudy?: string;
  location?: string | null;
  startYear?: number;
  endYear?: number | null;
  isOngoing?: boolean;
  description?: string | null;
  gpa?: string | null;
  finalProjectTitle?: string | null;
  finalProjectUrl?: string | null;
  order?: number;
};

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

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

    const formData = new FormData(e.currentTarget);
    let result;

    if (educationId) {
      result = await updateEducationAction(educationId, null, formData);
    } else {
      result = await createEducationAction(null, formData);
    }

    if (!result.success) {
      setError(result.message || "An error occurred");
      setLoading(false);
      return;
    }

    router.push("/admin/dashboard/education");
    router.refresh();
  }

  return (
    <div className="max-w-3xl 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-sky-500 to-indigo-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>
          <div className="flex items-center gap-3 mb-1">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-500 text-white flex items-center justify-center shadow-lg">
              <GraduationCap size={18} />
            </div>
            <h1 className="text-2xl font-bold tracking-tight">
              {educationId ? "Edit Education" : "Add Education"}
            </h1>
          </div>
          <p className="text-sm text-muted-foreground">
            {educationId
              ? "Update your academic timeline entry"
              : "Add a new entry to your education history"}
          </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">Institution</label>
            <input
              name="institution"
              required
              defaultValue={initialData?.institution ?? ""}
              placeholder="e.g. Universitas Indonesia"
              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-sky-500/50 transition-all"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">Location</label>
            <input
              name="location"
              defaultValue={initialData?.location ?? ""}
              placeholder="e.g. Depok, Indonesia"
              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-sky-500/50 transition-all"
            />
          </div>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Degree</label>
            <input
              name="degree"
              required
              defaultValue={initialData?.degree ?? ""}
              placeholder="e.g. Bachelor of Computer Science"
              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-sky-500/50 transition-all"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">Field of Study</label>
            <input
              name="fieldOfStudy"
              required
              defaultValue={initialData?.fieldOfStudy ?? ""}
              placeholder="e.g. Information Systems"
              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-sky-500/50 transition-all"
            />
          </div>
        </div>

        <div className="grid md:grid-cols-3 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">Start Year</label>
            <input
              name="startYear"
              type="number"
              min="1900"
              max="2100"
              required
              defaultValue={initialData?.startYear ?? ""}
              placeholder="2019"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm font-mono focus:outline-none focus:ring-2 focus:ring-sky-500/50 transition-all"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">End Year</label>
            <input
              name="endYear"
              type="number"
              min="1900"
              max="2100"
              disabled={isOngoing}
              defaultValue={initialData?.endYear ?? ""}
              placeholder={isOngoing ? "Still ongoing" : "2023"}
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm font-mono focus:outline-none focus:ring-2 focus:ring-sky-500/50 transition-all disabled:opacity-50"
            />
          </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 font-mono focus:outline-none focus:ring-2 focus:ring-sky-500/50 transition-all"
            />
          </div>
        </div>

        <div className="flex items-center gap-3 pt-1">
          <input
            id="isOngoing"
            name="isOngoing"
            type="checkbox"
            checked={isOngoing}
            onChange={(e) => setIsOngoing(e.target.checked)}
            className="w-5 h-5 rounded border-border text-sky-500 focus:ring-sky-500/50"
          />
          <label htmlFor="isOngoing" className="text-sm font-medium cursor-pointer">
            This education entry is ongoing
          </label>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-sm font-semibold">GPA</label>
            <input
              name="gpa"
              defaultValue={initialData?.gpa ?? ""}
              placeholder="e.g. 3.85 / 4.00"
              className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm font-mono focus:outline-none focus:ring-2 focus:ring-sky-500/50 transition-all"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-semibold">Final Project Title</label>
            <input
              name="finalProjectTitle"
              defaultValue={initialData?.finalProjectTitle ?? ""}
              placeholder="e.g. Sistem Monitoring Distribusi Dokumen"
              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-sky-500/50 transition-all"
            />
          </div>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Final Project URL</label>
          <input
            name="finalProjectUrl"
            type="url"
            defaultValue={initialData?.finalProjectUrl ?? ""}
            placeholder="https://repository.example.edu/final-project"
            className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm font-mono focus:outline-none focus:ring-2 focus:ring-sky-500/50 transition-all"
          />
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold">Description</label>
          <textarea
            name="description"
            rows={4}
            defaultValue={initialData?.description ?? ""}
            placeholder="Describe the focus of your studies, thesis theme, or relevant specialization..."
            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-sky-500/50 transition-all 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" />
            ) : educationId ? (
              <><Save size={18} /> Update</>
            ) : (
              <><PlusCircle size={18} /> Save Education</>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
