"use client";

import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { getProfile, updateProfile, uploadProfileImage } from "../../lib/auth";
import PlaceAutocomplete from "../PlaceAutocomplete";
import ProfileAvatar from "../ProfileAvatar";

interface Props {
  show: boolean;
  onClose: () => void;
  user: any;
  onUpdated: (user: any) => void;
}

export default function EditProfileModal({
  show,
  onClose,
  user,
  onUpdated,
}: Props) {
  const [loading, setLoading] = useState(false);

  const [profileData, setProfileData] = useState<any>(null);

  const [pincodeError, setPincodeError] = useState("");

  const [uploading, setUploading] = useState(false);

  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const [form, setForm] = useState({
    id: "",
    name: "",
    email: "",
    birthDate: "",
    birthTime: "",
    profile: "",
    birthPlace: "",
    addressLine1: "",
    location: "",
    pincode: "",
    gender: "",
    countryCode: "91",
    contactNo: "",
  });

  useEffect(() => {
    if (show) {
      loadProfile();
    }
  }, [show]);

  const loadProfile = async () => {
    try {
      const token = localStorage.getItem("token");

      if (!token) return;

      const response = await getProfile(token);

      const u = response.user;

      setProfileData(u);

      setPincodeError("");

      setForm({
        id: u.Id,
        name: u.Name || "",
        email: u.Email || "",
        birthDate: u.BirthDate || "",
        birthTime: u.BirthTime || "",
        profile: u.Name || "",
        birthPlace: u.BirthPlace || "",
        addressLine1: u.AddressLine1 || "",
        location: u.Location || "",
        pincode: u.Pincode || "",
        gender: u.Gender || "",
        countryCode: u.CountryCode || "91",
        contactNo: u.ContactNo || "",
      });
    } catch (err) {
      console.log(err);
    }
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });

    if (e.target.name === "pincode") {
      setPincodeError("");
    }
  };

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

    // Allow picking the same file again later.
    e.target.value = "";

    if (!file) return;

    const objectUrl = URL.createObjectURL(file);

    setPreviewUrl(objectUrl);

    try {
      setUploading(true);

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

      if (!token) {
        toast.error("Login expired");
        return;
      }

      const result = await uploadProfileImage(file, token);

      // The backend uses more than one response envelope across
      // endpoints — {status:false,...} on some, {success:false,...}
      // on others (confirmed on an auth error here) — check both.
      if (result?.status === false || result?.success === false) {
        toast.error(result?.message || "Failed to upload photo");
        return;
      }

      // Re-fetch the canonical profile rather than trust the
      // upload response's shape (undocumented in the API collection).
      const latest = await getProfile(token);

      setProfileData(latest.user);

      localStorage.setItem("user", JSON.stringify(latest.user));

      window.dispatchEvent(new Event("profile-updated"));

      toast.success("Profile photo updated");
    } catch (err: any) {
      toast.error(
        err.response?.data?.message || "Something went wrong while uploading"
      );
    } finally {
      setUploading(false);

      setPreviewUrl(null);

      URL.revokeObjectURL(objectUrl);
    }
  };

  const submit = async () => {
    if (!form.pincode) {
      setPincodeError("Pincode is required");
      return;
    }

    if (!/^[0-9]{6}$/.test(form.pincode)) {
      setPincodeError("Enter a valid 6-digit pincode");
      return;
    }

    setPincodeError("");

    try {
      setLoading(true);

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

      if (!token) return;

      const payload = {
        id: Number(form.id),
        name: form.name,
        email: form.email,
        birthDate: form.birthDate,
        birthTime: form.birthTime,
        profile: form.profile,
        birthPlace: form.birthPlace,
        addressLine1: form.addressLine1,
        location: form.location,
        pincode: form.pincode,
        gender: form.gender,
        countryCode: form.countryCode,
        contactNo: form.contactNo,
      };

      const response = await updateProfile(payload, token);

      if (response.success) {
        toast.success("Profile Updated Successfully");

        const latest = await getProfile(token);

        localStorage.setItem(
          "user",
          JSON.stringify(latest.user)
        );

        onUpdated(latest.user);

        window.dispatchEvent(new Event("profile-updated"));

        onClose();
      } else {
        toast.error("Update Failed");
      }
    } catch (err: any) {
      toast.error(
        err.response?.data?.message || "Something went wrong"
      );
    } finally {
      setLoading(false);
    }
  };

  if (!show) return null;

  return (
    <div
      className="modal fade show d-block"
      style={{
        background: "rgba(0,0,0,.65)",
      }}
    >
      <div className="modal-dialog modal-xl modal-dialog-centered">
        <div className="modal-content card-bg-primary border-0 rounded-4 overflow-hidden">

          <div className="modal-header bg-warning border-0">

            <h4 className="modal-title w-100 text-center fw-bold">
              Edit Your Profile
            </h4>

            <button
              className="btn-close"
              onClick={onClose}
            ></button>

          </div>

          <div className="modal-body  p-3 p-md-4">

            <div className="text-center mb-4">

              <div
                style={{
                  position: "relative",
                  display: "inline-block",
                  cursor: uploading ? "default" : "pointer",
                  opacity: uploading ? 0.6 : 1,
                }}
                onClick={() => !uploading && fileInputRef.current?.click()}
                title="Change profile photo"
              >
                <ProfileAvatar
                  user={profileData}
                  size={120}
                  className="border"
                  overrideSrc={previewUrl}
                />

                <span
                  style={{
                    position: "absolute",
                    bottom: 2,
                    right: 2,
                    width: 34,
                    height: 34,
                    borderRadius: "50%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: "#f8c100",
                    border: "2px solid #1a1206",
                    fontSize: 15,
                  }}
                >
                  {uploading ? "…" : "📷"}
                </span>
              </div>

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

            </div>

            <div className="row g-3 text-white">

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">Name</label>

                <input
                  name="name"
                  className="form-control form-control-lg"
                  value={form.name}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">Email</label>

                <input
                  name="email"
                  className="form-control form-control-lg"
                  value={form.email}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">
                  Gender
                </label>

                <div className="d-flex gap-2 gender-wrapper">

                  <button
                    type="button"
                    className={`gender-btn ${
                      form.gender === "Male" ? "active" : ""
                    }`}
                    onClick={() =>
                      setForm({
                        ...form,
                        gender: "Male",
                      })
                    }
                  >
                    Male
                  </button>

                  <button
                    type="button"
                    className={`gender-btn ${
                      form.gender === "Female" ? "active" : ""
                    }`}
                    onClick={() =>
                      setForm({
                        ...form,
                        gender: "Female",
                      })
                    }
                  >
                    Female
                  </button>

                  {/* <button
                    type="button"
                    className={`gender-btn ${
                      form.gender === "Other" ? "active" : ""
                    }`}
                    onClick={() =>
                      setForm({
                        ...form,
                        gender: "Other",
                      })
                    }
                  >
                    Other
                  </button> */}

                </div>
              </div>

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">Date of Birth</label>

                <input
                  type="date"
                  name="birthDate"
                  className="form-control form-control-lg"
                  value={form.birthDate}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">Birth Time</label>

                <input
                  type="time"
                  name="birthTime"
                  className="form-control form-control-lg"
                  value={form.birthTime}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-4">
                <PlaceAutocomplete
                  label="Birth Place"
                  placeholder="Search Birth Place"
                  value={form.birthPlace}
                  onChange={(value) =>
                    setForm({
                      ...form,
                      birthPlace: value,
                    })
                  }
                />
              </div>

              <div className="col-md-12">
                <label className="form-label fw-bold text-white">Current Address</label>

                <input
                  name="addressLine1"
                  className="form-control form-control-lg"
                  value={form.addressLine1}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-4">
                <PlaceAutocomplete
                  label="City, State, Country"
                  placeholder="Search City"
                  value={form.location}
                  onChange={(value) =>
                    setForm({
                      ...form,
                      location: value,
                    })
                  }
                  onSelect={(details) => {
                    if (details.pincode) {
                      setForm((prev) => ({ ...prev, pincode: details.pincode }));
                      setPincodeError("");
                    }
                  }}
                />
              </div>

              <div className="col-md-4">
                <label className="form-label fw-bold text-white">Pincode</label>

                <input
                  name="pincode"
                  type="text"
                  inputMode="numeric"
                  maxLength={6}
                  className={`form-control form-control-lg ${
                    pincodeError ? "is-invalid" : ""
                  }`}
                  value={form.pincode}
                  onChange={handleChange}
                />

                {pincodeError && (
                  <div className="invalid-feedback">
                    {pincodeError}
                  </div>
                )}
              </div>

              <div className="col-md-4">

                  <label className="form-label fw-bold text-white">
                    Mobile Number
                  </label>

                  <input
                    className="form-control form-control-lg"
                    value={form.contactNo}
                    readOnly
                  />

                </div>

            </div>

          </div>

          <div className="modal-footer justify-content-center border-0">

            <button
              className="btn btn-primary px-5"
              disabled={loading}
              onClick={submit}
            >
              {loading
                ? "Updating..."
                : "Update Profile"}
            </button>

          </div>

        </div>
      </div>
    </div>
  );
}