"use client";

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

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

  const fileInputRef = useRef<HTMLInputElement>(null);

  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const picked = e.target.files?.[0];

    e.target.value = "";

    if (!picked) return;

    setFile(picked);
    setPreviewUrl(URL.createObjectURL(picked));
  };

  const handleSave = async () => {
    if (!file) {
      toast.error("Please select a photo");
      return;
    }

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

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

    try {
      setLoading(true);

      const response = await uploadAstrologerProfileImage(file, token);

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

      toast.success("Photo saved");

      router.push("/astrologer/profile/progress");
    } catch {
      toast.error("Unable to upload the photo.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
    <Header />
    <StepShell step={4} title="Upload image" loading={loading} onSave={handleSave}>
      <div className="astrologer-upload-card">
        <div
          className="rounded-circle mx-auto mb-3 d-flex align-items-center justify-content-center"
          style={{
            width: 110,
            height: 110,
            border: "1px solid rgba(255,255,255,.2)",
            overflow: "hidden",
          }}
        >
          {previewUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={previewUrl}
              alt="Profile"
              style={{ width: "100%", height: "100%", objectFit: "cover" }}
            />
          ) : (
            <span className="terms-text-color small">no photo</span>
          )}
        </div>

        <p className="terms-text-color small">
          Face centred and clearly lit. Users see this at 72 px, so
          avoid group photos and text overlays.
        </p>

        <button
          type="button"
          className="btn btn-primary w-100"
          onClick={() => fileInputRef.current?.click()}
          disabled={loading}
        >
          {previewUrl ? "Change photo" : "Upload"}
        </button>

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

      <div className="terms-text-color small">
        <div>&bull; Square crop, at least 600 x 600</div>
        <div>&bull; JPG or PNG under 2 MB</div>
        <div>&bull; No watermark or contact details</div>
      </div>
    </StepShell>
    <Footer />
    </>
  );
}
