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

interface Experience {
  title: string;
  experience_years: string;
  description: string;
  start_year: string;
  end_year: string;
  currently_working: boolean;
}

const EMPTY: Experience = {
  title: "",
  experience_years: "",
  description: "",
  start_year: "",
  end_year: "",
  currently_working: false,
};

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

  const [items, setItems] = useState<Experience[]>([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 experiences: any[] = p?.experiences ?? [];

        if (!experiences.length) return;

        // Confirmed live: GET /astrologer/profile's `experiences[]`
        // has `is_current` — no `start_year`/`end_year` (not returned
        // by this endpoint) and no `currently_working` field name.
        setItems(
          experiences.map((item) => ({
            title: item.title ?? "",
            experience_years: item.experience_years?.toString() ?? "",
            description: item.description ?? "",
            start_year: "",
            end_year: "",
            currently_working: !!item.is_current,
          }))
        );
      })
      .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.title)
        .map((item) => ({
          title: item.title,
          experience_years: Number(item.experience_years) || 0,
          description: item.description,
          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 updateExperience(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={7} title="Experiences" 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">
                Title
              </label>
              <input
                className="form-control form-control-lg"
                value={item.title}
                onChange={(e) => update({ title: 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="mb-3">
              <label className="form-label terms-text-color small">
                Description
              </label>
              <textarea
                className="form-control form-control-lg"
                rows={3}
                maxLength={500}
                value={item.description}
                onChange={(e) => update({ description: 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>
  );
}
