"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 RepeatableCardList from "@/app/components/astrologer/RepeatableCardList";
import {
  updateProfessional,
  getAstrologerProfile,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";

interface Professional {
  company_name: string;
  designation: string;
  experience_years: string;
  start_year: string;
  end_year: string;
  currently_working: boolean;
}

const EMPTY: Professional = {
  company_name: "",
  designation: "",
  experience_years: "",
  start_year: "",
  end_year: "",
  currently_working: false,
};

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

  const [items, setItems] = useState<Professional[]>([EMPTY]);
  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 professionals: any[] = p?.professionals ?? [];

        if (!professionals.length) return;

        // Confirmed live: GET /astrologer/profile's `professionals[]`
        // has `occupation`/`current_company` — no `company_name`/
        // `designation` (what the save payload uses) — alias them.
        setItems(
          professionals.map((item) => ({
            company_name: item.current_company ?? "",
            designation: item.occupation ?? "",
            experience_years: item.experience_years?.toString() ?? "",
            start_year: item.start_year ? item.start_year.toString() : "",
            end_year: item.end_year ? item.end_year.toString() : "",
            currently_working: !!item.currently_working,
          }))
        );
      })
      .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 = items
        .filter((item) => item.company_name)
        .map((item) => ({
          company_name: item.company_name,
          designation: item.designation,
          experience_years: Number(item.experience_years) || 0,
          start_year: Number(item.start_year) || undefined,
          end_year: item.currently_working
            ? undefined
            : Number(item.end_year) || undefined,
          currently_working: item.currently_working,
        }));

      const response = await updateProfessional(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={6} title="Professional" mode="edit" loading={loading} onSave={handleSave}>
      <RepeatableCardList
        items={items}
        onChange={setItems}
        emptyItem={EMPTY}
        addLabel="Add Another Experience"
        renderItem={(item, update) => (
          <>
            <div className="mb-3">
              <label className="form-label terms-text-color small">
                Company name
              </label>
              <input
                className="form-control form-control-lg"
                value={item.company_name}
                onChange={(e) => update({ company_name: e.target.value })}
              />
            </div>

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

            <div className="mb-3">
              <label className="form-label terms-text-color small">
                Experience years
              </label>
              <input
                type="number"
                className="form-control form-control-lg"
                value={item.experience_years}
                onChange={(e) =>
                  update({ experience_years: e.target.value })
                }
              />
            </div>

            <div className="row g-3 mb-3">
              <div className="col-6">
                <label className="form-label terms-text-color small">
                  Start year
                </label>
                <input
                  className="form-control form-control-lg"
                  value={item.start_year}
                  onChange={(e) =>
                    update({
                      start_year: e.target.value.replace(/\D/g, "").slice(0, 4),
                    })
                  }
                />
              </div>

              <div className="col-6">
                <label className="form-label terms-text-color small">
                  End year
                </label>
                <input
                  className="form-control form-control-lg"
                  disabled={item.currently_working}
                  value={item.end_year}
                  onChange={(e) =>
                    update({
                      end_year: e.target.value.replace(/\D/g, "").slice(0, 4),
                    })
                  }
                />
              </div>
            </div>

            <div className="form-check form-switch">
              <input
                className="form-check-input"
                type="checkbox"
                checked={item.currently_working}
                onChange={(e) =>
                  update({ currently_working: e.target.checked })
                }
              />
              <label className="form-check-label">
                Currently working here
              </label>
            </div>
          </>
        )}
      />
    </StepShell>
  );
}
