"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";

import StepShell from "@/app/components/astrologer/StepShell";
import PillMultiSelect from "@/app/components/astrologer/PillMultiSelect";
import { getMasterLanguages, saveLanguages, friendlyErrorMessage } from "@/app/lib/astrologer";

interface Option {
  id: number;
  label: string;
}

// Master-data response shape isn't confirmed in the Postman collection
// (no sample response) — unwrap defensively, same pattern this project
// already uses for the Go backend's other unconfirmed envelopes.
function extractOptions(response: any): Option[] {
  const list =
    response?.data?.languages ??
    response?.data ??
    response?.languages ??
    response ??
    [];

  if (!Array.isArray(list)) return [];

  return list.map((item: any) => ({
    id: item.id ?? item.language_id,
    label:
      item.language_name ??
      item.name ??
      item.language ??
      item.title ??
      String(item.id),
  }));
}

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

  const [options, setOptions] = useState<Option[]>([]);
  const [selected, setSelected] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);

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

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

    getMasterLanguages(token)
      .then((response) => setOptions(extractOptions(response)))
      .catch(() => toast.error("Unable to load languages."));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSave = async () => {
    if (selected.length === 0) {
      toast.error("Choose at least one language");
      return;
    }

    const token = localStorage.getItem("astrologerToken");

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

    try {
      setLoading(true);

      const response = await saveLanguages(selected, token);

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

      toast.success("Saved");

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

  return (
    <>
    <Header />
    <StepShell step={2} title="Choose Languages" loading={loading} onSave={handleSave}>
      <PillMultiSelect options={options} selectedIds={selected} onChange={setSelected} />
    </StepShell>
    <Footer />
    </>
  );
}
