"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import StepShell from "@/app/components/astrologer/StepShell";
import {
  updateEducation,
  getAstrologerProfile,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";

interface Degree {
  degree: string;
  institute: string;
  field_of_study: string;
  passing_year: string;
}

const EMPTY_DEGREE: Degree = {
  degree: "",
  institute: "",
  field_of_study: "",
  passing_year: "",
};

function DegreeFields({
  label,
  value,
  onChange,
}: {
  label: string;
  value: Degree;
  onChange: (patch: Partial<Degree>) => void;
}) {
  return (
    <div className="astrologer-repeat-card">
      <div className="fw-semibold mb-3">{label}</div>

      <div className="mb-3">
        <label className="form-label terms-text-color small">Degree</label>
        <input
          className="form-control form-control-lg"
          value={value.degree}
          onChange={(e) => onChange({ degree: e.target.value })}
        />
      </div>

      <div className="row g-3 mb-3">
        <div className="col-8">
          <label className="form-label terms-text-color small">
            Institute
          </label>
          <input
            className="form-control form-control-lg"
            value={value.institute}
            onChange={(e) => onChange({ institute: e.target.value })}
          />
        </div>

        <div className="col-4">
          <label className="form-label terms-text-color small">Year</label>
          <input
            className="form-control form-control-lg"
            value={value.passing_year}
            onChange={(e) =>
              onChange({
                passing_year: e.target.value.replace(/\D/g, "").slice(0, 4),
              })
            }
          />
        </div>
      </div>

      <div>
        <label className="form-label terms-text-color small">
          Field of study
        </label>
        <input
          className="form-control form-control-lg"
          value={value.field_of_study}
          onChange={(e) => onChange({ field_of_study: e.target.value })}
        />
      </div>
    </div>
  );
}

export default function EditEducationPage() {
  const router = useRouter();

  const [ug, setUg] = useState<Degree>(EMPTY_DEGREE);
  const [pg, setPg] = useState<Degree>(EMPTY_DEGREE);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    getAstrologerProfile(token)
      .then((response) => {
        const p = response.data ?? response;
        const educations: any[] = p?.educations ?? [];

        // Confirmed live: GET /astrologer/profile returns a flat
        // `educations[]` array with an `EducationType` ("UG"/"PG")
        // discriminator and a `specialization` field, not the nested
        // `ug`/`pg` keys or `field_of_study` name the save payload uses.
        const toDegree = (e: any): Degree | null =>
          e
            ? {
                degree: e.degree ?? "",
                institute: e.institute ?? "",
                field_of_study: e.specialization ?? e.field_of_study ?? "",
                passing_year: e.passing_year?.toString() ?? "",
              }
            : null;

        const ugEntry = educations.find((e) => e.EducationType === "UG");
        const pgEntry = educations.find((e) => e.EducationType === "PG");

        const mappedUg = toDegree(ugEntry);
        const mappedPg = toDegree(pgEntry);

        if (mappedUg) setUg(mappedUg);
        if (mappedPg) setPg(mappedPg);
      })
      .catch(() => {});
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSave = async () => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    try {
      setLoading(true);

      const payload = {
        ug: {
          ...ug,
          passing_year: Number(ug.passing_year) || undefined,
        },
        pg: {
          ...pg,
          passing_year: Number(pg.passing_year) || undefined,
        },
      };

      const response = await updateEducation(payload, token);

      if (!response.success) {
        toast.error(friendlyErrorMessage(response.message, "Unable to save. Please try again."));
        return;
      }

      toast.success("Saved");

      router.push("/astrologer/profile");
    } catch (error: any) {
      toast.error(friendlyErrorMessage(error.response?.data?.message, "Something went wrong."));
    } finally {
      setLoading(false);
    }
  };

  return (
    <StepShell step={5} title="Choose Education" mode="edit" loading={loading} onSave={handleSave}>
      <DegreeFields
        label="(UG) Degree"
        value={ug}
        onChange={(patch) => setUg((prev) => ({ ...prev, ...patch }))}
      />

      <DegreeFields
        label="PG - Degree"
        value={pg}
        onChange={(patch) => setPg((prev) => ({ ...prev, ...patch }))}
      />
    </StepShell>
  );
}
