"use client";

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

interface BasicForm {
  name: string;
  displayName: string;
  gender: string;
  marital_status: string;
  date_of_birth: string;
  bio: string;
  primary_skills: string;
  primary_language: string;
  experience_years: string;
  daily_hours: string;
  working_platform: boolean;
  working_platform_name: string;
  learn_astrology: string;
  address: string;
  city: string;
  pincode: string;
  state: string;
  country: string;
}

const EMPTY: BasicForm = {
  name: "",
  displayName: "",
  gender: "",
  marital_status: "",
  date_of_birth: "",
  bio: "",
  primary_skills: "",
  primary_language: "",
  experience_years: "",
  daily_hours: "",
  working_platform: false,
  working_platform_name: "",
  learn_astrology: "",
  address: "",
  city: "",
  pincode: "",
  state: "",
  country: "India",
};

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

  const [form, setForm] = useState<BasicForm>(EMPTY);
  const [loading, setLoading] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const [photoUrl, setPhotoUrl] = useState<string | null>(null);
  const [photoUploading, setPhotoUploading] = useState(false);

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

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

    getAstrologerProfile(token)
      .then((response) => {
        const p = response.data ?? response;

        if (!p) return;

        setPhotoUrl(p.ProfileImage || p.profile_image || null);

        // Confirmed live: GET /astrologer/profile returns PascalCase
        // GORM field names, different from the snake_case the
        // wizard-step *save* endpoints expect — alias both.
        setForm((prev) => ({
          ...prev,
          name: p.name ?? p.Name ?? prev.name,
          displayName: p.displayName ?? p.Display_name ?? prev.displayName,
          gender: p.gender ?? p.Gender ?? prev.gender,
          marital_status: p.marital_status ?? prev.marital_status,
          date_of_birth:
            (p.date_of_birth ?? p.birth_date ?? prev.date_of_birth)?.slice?.(
              0,
              10
            ) ?? prev.date_of_birth,
          bio: p.bio ?? p.loginBio ?? prev.bio,
          primary_skills: p.primary_skills ?? p.PrimarySkill ?? prev.primary_skills,
          primary_language:
            p.primary_language ?? p.LanguageKnown ?? prev.primary_language,
          experience_years:
            (p.experience_years ?? p.ExperienceYears)?.toString() ??
            prev.experience_years,
          daily_hours:
            (p.daily_hours ?? p.dailyContribution)?.toString() ??
            prev.daily_hours,
          working_platform: p.working_platform ?? p.isWorkingOnAnotherPlatform ?? prev.working_platform,
          working_platform_name: p.working_platform_name ?? p.nameofplateform ?? prev.working_platform_name,
          learn_astrology: p.learn_astrology ?? p.learnAstrology ?? prev.learn_astrology,
          address: p.address ?? prev.address,
          city: p.city ?? p.currentCity ?? prev.city,
          pincode: p.pincode ?? prev.pincode,
          state: p.state ?? prev.state,
          country: p.country || p.countary || prev.country,
        }));
      })
      .catch(() => {});
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const update = (patch: Partial<BasicForm>) =>
    setForm((prev) => ({ ...prev, ...patch }));

  // Fires its own API call the moment a file is picked — independent
  // of the "Update Profile" button below, which only ever saves the
  // text fields.
  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    e.target.value = "";

    if (!file) return;

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

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

    const previousUrl = photoUrl;
    const previewUrl = URL.createObjectURL(file);
    setPhotoUrl(previewUrl);

    try {
      setPhotoUploading(true);

      const response = await updateAstrologerProfileImage(file, token);

      if (!response.success) {
        toast.error(friendlyErrorMessage(response.message, "Unable to update photo."));
        setPhotoUrl(previousUrl);
        return;
      }

      toast.success("Profile photo updated");
    } catch (error: any) {
      toast.error(friendlyErrorMessage(error.response?.data?.message, "Unable to update photo."));
      setPhotoUrl(previousUrl);
    } finally {
      setPhotoUploading(false);
    }
  };

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

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

    if (!form.name || !form.displayName || !form.gender || !form.date_of_birth) {
      toast.error("Please fill all required fields");
      return;
    }

    try {
      setLoading(true);

      // Confirmed against the real Postman "Update Profile" body:
      // only these fields are accepted — displayName/marital_status/
      // primary_skills/primary_language aren't part of it (sent anyway
      // since extra fields are harmless), but working_platform/
      // working_platform_name/learn_astrology ARE required by it.
      const payload = {
        ...form,
        experience_years: Number(form.experience_years) || 0,
        daily_hours: Number(form.daily_hours) || 0,
      };

      const response = await updateAstrologerProfile(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={1} title="Basic Details" mode="edit" loading={loading} onSave={handleSave}>
      <div className="astrologer-repeat-card mb-4 d-flex align-items-center gap-3">
        {photoUrl ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={photoUrl}
            alt=""
            className="rounded-circle"
            style={{ width: 64, height: 64, objectFit: "cover", border: "2px solid #ffd700" }}
          />
        ) : (
          <div
            className="rounded-circle d-flex align-items-center justify-content-center bg-warning text-dark fw-bold"
            style={{ width: 64, height: 64, fontSize: 22 }}
          >
            {(form.name || "A").trim().charAt(0).toUpperCase()}
          </div>
        )}

        <div className="flex-fill">
          <div className="text-white fw-semibold">Profile photo</div>
          <small className="terms-text-color">
            Saves on its own — not with this form.
          </small>
        </div>

        <button
          type="button"
          className="btn btn-outline-light btn-sm"
          onClick={() => fileInputRef.current?.click()}
          disabled={photoUploading}
        >
          {photoUploading ? "Uploading..." : "📷 Change"}
        </button>

        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          style={{ display: "none" }}
          onChange={handlePhotoChange}
        />
      </div>

      <h6 className="mb-3">Who you are</h6>

      <div className="mb-3">
        <label className="form-label fw-semibold">Full name *</label>
        <input
          className="form-control form-control-lg"
          value={form.name}
          onChange={(e) => update({ name: e.target.value })}
        />
      </div>

      <div className="mb-3">
        <label className="form-label fw-semibold">Display name *</label>
        <input
          className="form-control form-control-lg"
          value={form.displayName}
          onChange={(e) => update({ displayName: e.target.value })}
        />
        <small className="terms-text-color">Shown to users on your card.</small>
      </div>

      <div className="row g-3 mb-3">
        <div className="col-6">
          <label className="form-label fw-semibold">Gender *</label>
          <select
            className="form-control form-control-lg"
            value={form.gender}
            onChange={(e) => update({ gender: e.target.value })}
          >
            <option value="">Select</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
            <option value="Other">Other</option>
          </select>
        </div>

        <div className="col-6">
          <label className="form-label fw-semibold">Marital status</label>
          <select
            className="form-control form-control-lg"
            value={form.marital_status}
            onChange={(e) => update({ marital_status: e.target.value })}
          >
            <option value="">Select</option>
            <option value="Single">Single</option>
            <option value="Married">Married</option>
          </select>
        </div>
      </div>

      <div className="mb-3">
        <label className="form-label fw-semibold">Date of birth *</label>
        <input
          type="date"
          className="form-control form-control-lg"
          value={form.date_of_birth}
          onChange={(e) => update({ date_of_birth: e.target.value })}
        />
      </div>

      <div className="mb-4">
        <label className="form-label fw-semibold">Bio</label>
        <textarea
          className="form-control form-control-lg"
          rows={3}
          value={form.bio}
          onChange={(e) => update({ bio: e.target.value })}
        />
        <small className="terms-text-color">
          Two or three lines. No contact details.
        </small>
      </div>

      <h6 className="mb-3">Practice</h6>

      <div className="row g-3 mb-3">
        <div className="col-6">
          <label className="form-label fw-semibold">Primary skill *</label>
          <input
            className="form-control form-control-lg"
            value={form.primary_skills}
            onChange={(e) => update({ primary_skills: e.target.value })}
          />
        </div>

        <div className="col-6">
          <label className="form-label fw-semibold">Primary language *</label>
          <input
            className="form-control form-control-lg"
            value={form.primary_language}
            onChange={(e) => update({ primary_language: e.target.value })}
          />
        </div>
      </div>

      <div className="row g-3 mb-4">
        <div className="col-6">
          <label className="form-label fw-semibold">Experience</label>
          <div className="input-group input-group-lg">
            <input
              type="number"
              className="form-control"
              value={form.experience_years}
              onChange={(e) => update({ experience_years: e.target.value })}
            />
            <span className="input-group-text">yrs</span>
          </div>
        </div>

        <div className="col-6">
          <label className="form-label fw-semibold">Daily hours</label>
          <div className="input-group input-group-lg">
            <input
              type="number"
              className="form-control"
              value={form.daily_hours}
              onChange={(e) => update({ daily_hours: e.target.value })}
            />
            <span className="input-group-text">hrs</span>
          </div>
        </div>
      </div>

      <div className="mb-4">
        <label className="form-label fw-semibold">
          How did you learn astrology?
        </label>
        <input
          className="form-control form-control-lg"
          value={form.learn_astrology}
          onChange={(e) => update({ learn_astrology: e.target.value })}
        />
      </div>

      <div className="mb-4">
        <div className="form-check form-switch mb-2">
          <input
            className="form-check-input"
            type="checkbox"
            checked={form.working_platform}
            onChange={(e) => update({ working_platform: e.target.checked })}
          />
          <label className="form-check-label small terms-text-color">
            I work on another astrology platform
          </label>
        </div>

        {form.working_platform && (
          <input
            placeholder="Which platform?"
            className="form-control form-control-lg"
            value={form.working_platform_name}
            onChange={(e) => update({ working_platform_name: e.target.value })}
          />
        )}
      </div>

      <h6 className="mb-3">Where you are</h6>

      <div className="mb-3">
        <label className="form-label fw-semibold">Address</label>
        <input
          placeholder="type here.."
          className="form-control form-control-lg"
          value={form.address}
          onChange={(e) => update({ address: e.target.value })}
        />
      </div>

      <div className="row g-3 mb-3">
        <div className="col-6">
          <label className="form-label fw-semibold">City</label>
          <input
            placeholder="type here.."
            className="form-control form-control-lg"
            value={form.city}
            onChange={(e) => update({ city: e.target.value })}
          />
        </div>

        <div className="col-6">
          <label className="form-label fw-semibold">Pincode</label>
          <input
            inputMode="numeric"
            maxLength={6}
            placeholder="0"
            className="form-control form-control-lg"
            value={form.pincode}
            onChange={(e) =>
              update({ pincode: e.target.value.replace(/\D/g, "").slice(0, 6) })
            }
          />
        </div>
      </div>

      <div className="row g-3">
        <div className="col-6">
          <label className="form-label fw-semibold">State</label>
          <input
            placeholder="type here.."
            className="form-control form-control-lg"
            value={form.state}
            onChange={(e) => update({ state: e.target.value })}
          />
        </div>

        <div className="col-6">
          <label className="form-label fw-semibold">Country</label>
          <input
            className="form-control form-control-lg"
            value={form.country}
            onChange={(e) => update({ country: e.target.value })}
          />
        </div>
      </div>
    </StepShell>
  );
}
