"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchProfile, updateProfile } from "@/store/slices/profileSlice";
import { fetchCities } from "@/store/slices/citySlice";
import { fetchLanguages } from "@/store/slices/languageSlice";
import { isAuthenticatedClient, getStoredUser } from "@/lib/utils/persistAuth";
import { useToast } from "@/lib/toast";

export default function EditProfileShell() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { success, error: showError } = useToast();
  const { user, isLoading, isUpdating } = useAppSelector((s) => s.profile);
  const { cities } = useAppSelector((s) => s.city);
  const { languages } = useAppSelector((s) => s.language);
  const fetchedRef = useRef(false);

  const [fullName, setFullName] = useState("");
  const [userName, setUserName] = useState("");
  const [email, setEmail] = useState("");
  const [bio, setBio] = useState("");
  const [mobile, setMobile] = useState("");
  const [countryCode, setCountryCode] = useState("+91");
  const [selectedCityIds, setSelectedCityIds] = useState<number[]>([]);
  const [selectedLangIds, setSelectedLangIds] = useState<number[]>([]);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string>("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!isAuthenticatedClient()) { router.replace("/login"); return; }
    if (!fetchedRef.current) {
      fetchedRef.current = true;
      const userId = getStoredUser()?.id ?? 0;
      dispatch(fetchProfile());
      dispatch(fetchCities({ userId }));
      dispatch(fetchLanguages({ userId }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Populate form when user loads
  useEffect(() => {
    if (user) {
      setFullName(user.full_name ?? "");
      setUserName(user.user_name ?? "");
      setEmail(user.email ?? "");
      setBio(user.bio ?? "");
      setMobile(user.mobile_number ?? "");
      setCountryCode(user.country_code || "+91");
      // Parse comma-separated IDs stored on the user
      if (user.city_id) {
        setSelectedCityIds(user.city_id.split(",").map(Number).filter(Boolean));
      }
      if (user.language_id) {
        setSelectedLangIds(user.language_id.split(",").map(Number).filter(Boolean));
      }
      if (user.image) {
        setImagePreview(user.image);
      }
    }
  }, [user]);

  function handleImageChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setImageFile(file);
    setImagePreview(URL.createObjectURL(file));
  }

  function toggleId(
    id: number,
    selected: number[],
    setSelected: (v: number[]) => void,
  ) {
    setSelected(
      selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id],
    );
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    let payload: FormData | Record<string, string>;
    if (imageFile) {
      const fd = new FormData();
      fd.append("full_name", fullName.trim());
      fd.append("user_name", userName.trim());
      fd.append("email", email.trim());
      fd.append("bio", bio.trim());
      fd.append("mobile_number", mobile.trim());
      fd.append("country_code", countryCode);
      fd.append("city_id", selectedCityIds.join(","));
      fd.append("language_id", selectedLangIds.join(","));
      fd.append("image", imageFile);
      payload = fd;
    } else {
      payload = {
        full_name: fullName.trim(),
        user_name: userName.trim(),
        email: email.trim(),
        bio: bio.trim(),
        mobile_number: mobile.trim(),
        country_code: countryCode,
        city_id: selectedCityIds.join(","),
        language_id: selectedLangIds.join(","),
      };
    }
    const res = await dispatch(updateProfile(payload));
    if (updateProfile.fulfilled.match(res)) {
      success("Profile updated successfully");
      router.push("/profile");
    } else {
      showError("Failed to update profile");
    }
  }

  const inputStyle: React.CSSProperties = {
    width: "100%",
    padding: "0.625rem 0.875rem",
    border: "1.5px solid var(--border, #e5e7eb)",
    borderRadius: 8,
    fontSize: "0.9375rem",
    color: "var(--ink, #0e0e11)",
    background: "var(--surf, #fff)",
    outline: "none",
    fontFamily: "inherit",
    boxSizing: "border-box",
    transition: "border-color 0.15s",
  };
  const labelStyle: React.CSSProperties = {
    display: "block",
    fontSize: "0.8125rem",
    fontWeight: 700,
    color: "var(--ink, #0e0e11)",
    marginBottom: "0.5rem",
    letterSpacing: "0.01em",
  };

  return (
    <main style={{ minHeight: "60vh", background: "var(--bg, #f8f9fb)", padding: "2rem 0" }}>
      <div className="wrap" style={{ maxWidth: 560, margin: "0 auto" }}>

        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", gap: "0.875rem", marginBottom: "1.75rem" }}>
          <button
            onClick={() => router.back()}
            style={{ background: "none", border: "none", cursor: "pointer", display: "flex", alignItems: "center", gap: 4, fontSize: "0.875rem", color: "var(--text-2, #6b7280)", fontWeight: 600, padding: 0 }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M19 12H5M12 5l-7 7 7 7" /></svg>
            Back
          </button>
          <h1 style={{ margin: 0, fontSize: "1.25rem", fontWeight: 800, color: "var(--ink, #0e0e11)", fontFamily: "var(--serif, Georgia, serif)" }}>
            Edit Profile
          </h1>
        </div>

        {isLoading && !user ? (
          <div style={{ background: "var(--surf, #fff)", border: "1px solid var(--border, #e5e7eb)", borderRadius: 12, padding: "2rem" }}>
            {Array.from({ length: 7 }).map((_, i) => (
              <div key={i} style={{ marginBottom: "1.25rem" }}>
                <div style={{ height: 11, width: "25%", background: "#e5e7eb", borderRadius: 4, marginBottom: 8 }} />
                <div style={{ height: 42, background: "#e5e7eb", borderRadius: 8 }} />
              </div>
            ))}
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <div style={{ background: "var(--surf, #fff)", border: "1px solid var(--border, #e5e7eb)", borderRadius: 12, padding: "1.5rem", display: "flex", flexDirection: "column", gap: "1.125rem" }}>

              {/* Profile image picker */}
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "0.75rem", paddingBottom: "0.5rem", borderBottom: "1px solid var(--border, #e5e7eb)" }}>
                <div
                  role="button"
                  tabIndex={0}
                  onClick={() => fileInputRef.current?.click()}
                  onKeyDown={(e) => e.key === "Enter" && fileInputRef.current?.click()}
                  style={{
                    position: "relative",
                    width: 88,
                    height: 88,
                    borderRadius: "50%",
                    cursor: "pointer",
                    overflow: "hidden",
                    border: "3px solid var(--brand, #C1272D)",
                    flexShrink: 0,
                  }}
                >
                  {imagePreview ? (
                    <Image
                      src={imagePreview}
                      alt="Profile"
                      fill
                      sizes="88px"
                      style={{ objectFit: "cover" }}
                      unoptimized
                    />
                  ) : (
                    <div style={{
                      width: "100%",
                      height: "100%",
                      background: "var(--brand-light, #fee2e2)",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: "1.75rem",
                      fontWeight: 800,
                      color: "var(--brand, #C1272D)",
                    }}>
                      {fullName ? fullName.charAt(0).toUpperCase() : "?"}
                    </div>
                  )}
                  {/* Camera overlay */}
                  <div style={{
                    position: "absolute",
                    inset: 0,
                    background: "rgba(0,0,0,0.45)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    opacity: 0,
                    transition: "opacity 0.15s",
                  }}
                    onMouseEnter={(e) => ((e.currentTarget as HTMLDivElement).style.opacity = "1")}
                    onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.opacity = "0")}
                  >
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round">
                      <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
                      <circle cx="12" cy="13" r="4" />
                    </svg>
                  </div>
                </div>
                <div style={{ textAlign: "center" }}>
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    style={{ background: "none", border: "none", cursor: "pointer", fontSize: "0.8125rem", fontWeight: 600, color: "var(--brand, #C1272D)", padding: 0 }}
                  >
                    {imageFile ? "Change Photo" : "Upload Photo"}
                  </button>
                  {imageFile && (
                    <button
                      type="button"
                      onClick={() => { setImageFile(null); setImagePreview(user?.image ?? ""); if (fileInputRef.current) fileInputRef.current.value = ""; }}
                      style={{ background: "none", border: "none", cursor: "pointer", fontSize: "0.8125rem", color: "var(--text-2, #6b7280)", padding: "0 0 0 12px" }}
                    >
                      Remove
                    </button>
                  )}
                  <p style={{ margin: "2px 0 0", fontSize: "0.75rem", color: "var(--text-3, #9ca3af)" }}>JPG, PNG or WEBP · max 5 MB</p>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  style={{ display: "none" }}
                  onChange={handleImageChange}
                />
              </div>

              <div>
                <label style={labelStyle}>Full Name</label>
                <input
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  placeholder="Your full name"
                  style={inputStyle}
                  onFocus={(e) => (e.target.style.borderColor = "var(--brand, #C1272D)")}
                  onBlur={(e) => (e.target.style.borderColor = "var(--border, #e5e7eb)")}
                />
              </div>

              <div>
                <label style={labelStyle}>Username</label>
                <input
                  value={userName}
                  onChange={(e) => setUserName(e.target.value)}
                  placeholder="@username"
                  style={inputStyle}
                  onFocus={(e) => (e.target.style.borderColor = "var(--brand, #C1272D)")}
                  onBlur={(e) => (e.target.style.borderColor = "var(--border, #e5e7eb)")}
                />
              </div>

              <div>
                <label style={labelStyle}>Email</label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="your@email.com"
                  style={inputStyle}
                  onFocus={(e) => (e.target.style.borderColor = "var(--brand, #C1272D)")}
                  onBlur={(e) => (e.target.style.borderColor = "var(--border, #e5e7eb)")}
                />
              </div>

              <div>
                <label style={labelStyle}>Mobile Number</label>
                <div style={{ display: "flex", gap: "0.5rem" }}>
                  <select
                    value={countryCode}
                    onChange={(e) => setCountryCode(e.target.value)}
                    style={{ ...inputStyle, width: 90, flexShrink: 0 }}
                  >
                    <option value="+91">+91</option>
                    <option value="+1">+1</option>
                    <option value="+44">+44</option>
                    <option value="+971">+971</option>
                  </select>
                  <input
                    value={mobile}
                    onChange={(e) => setMobile(e.target.value)}
                    placeholder="Phone number"
                    style={inputStyle}
                    onFocus={(e) => (e.target.style.borderColor = "var(--brand, #C1272D)")}
                    onBlur={(e) => (e.target.style.borderColor = "var(--border, #e5e7eb)")}
                  />
                </div>
              </div>

              <div>
                <label style={labelStyle}>Bio</label>
                <textarea
                  value={bio}
                  onChange={(e) => setBio(e.target.value)}
                  placeholder="Tell readers about yourself…"
                  rows={3}
                  style={{ ...inputStyle, resize: "none" }}
                  onFocus={(e) => (e.target.style.borderColor = "var(--brand, #C1272D)")}
                  onBlur={(e) => (e.target.style.borderColor = "var(--border, #e5e7eb)")}
                />
              </div>

              {/* City multi-select */}
              <div>
                <label style={labelStyle}>
                  Cities
                  {selectedCityIds.length > 0 && (
                    <span style={{ marginLeft: 6, fontWeight: 400, color: "var(--text-2, #6b7280)" }}>
                      ({selectedCityIds.length} selected)
                    </span>
                  )}
                </label>
                <div style={{
                  display: "flex",
                  flexWrap: "wrap",
                  gap: "0.5rem",
                  padding: "0.625rem",
                  border: "1.5px solid var(--border, #e5e7eb)",
                  borderRadius: 8,
                  background: "var(--surf, #fff)",
                  minHeight: 48,
                }}>
                  {cities.length === 0 ? (
                    <span style={{ fontSize: "0.8125rem", color: "var(--text-3, #9ca3af)" }}>Loading cities…</span>
                  ) : cities.map((city) => {
                    const active = selectedCityIds.includes(city.id);
                    return (
                      <button
                        key={city.id}
                        type="button"
                        onClick={() => toggleId(city.id, selectedCityIds, setSelectedCityIds)}
                        style={{
                          padding: "0.25rem 0.75rem",
                          borderRadius: 20,
                          fontSize: "0.8125rem",
                          fontWeight: 600,
                          cursor: "pointer",
                          border: active ? "1.5px solid var(--brand, #C1272D)" : "1.5px solid var(--border, #e5e7eb)",
                          background: active ? "var(--brand-light, #fee2e2)" : "transparent",
                          color: active ? "var(--brand, #C1272D)" : "var(--ink, #0e0e11)",
                          transition: "all 0.15s",
                        }}
                      >
                        {city.name}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Language multi-select */}
              <div>
                <label style={labelStyle}>
                  Languages
                  {selectedLangIds.length > 0 && (
                    <span style={{ marginLeft: 6, fontWeight: 400, color: "var(--text-2, #6b7280)" }}>
                      ({selectedLangIds.length} selected)
                    </span>
                  )}
                </label>
                <div style={{
                  display: "flex",
                  flexWrap: "wrap",
                  gap: "0.5rem",
                  padding: "0.625rem",
                  border: "1.5px solid var(--border, #e5e7eb)",
                  borderRadius: 8,
                  background: "var(--surf, #fff)",
                  minHeight: 48,
                }}>
                  {languages.length === 0 ? (
                    <span style={{ fontSize: "0.8125rem", color: "var(--text-3, #9ca3af)" }}>Loading languages…</span>
                  ) : languages.map((lang) => {
                    const active = selectedLangIds.includes(lang.id);
                    return (
                      <button
                        key={lang.id}
                        type="button"
                        onClick={() => toggleId(lang.id, selectedLangIds, setSelectedLangIds)}
                        style={{
                          padding: "0.25rem 0.75rem",
                          borderRadius: 20,
                          fontSize: "0.8125rem",
                          fontWeight: 600,
                          cursor: "pointer",
                          border: active ? "1.5px solid var(--brand, #C1272D)" : "1.5px solid var(--border, #e5e7eb)",
                          background: active ? "var(--brand-light, #fee2e2)" : "transparent",
                          color: active ? "var(--brand, #C1272D)" : "var(--ink, #0e0e11)",
                          transition: "all 0.15s",
                        }}
                      >
                        {lang.name}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div style={{ display: "flex", gap: "0.75rem", paddingTop: "0.5rem" }}>
                <button
                  type="button"
                  onClick={() => router.back()}
                  style={{ flex: 1, padding: "0.625rem", background: "none", border: "1.5px solid var(--border, #e5e7eb)", borderRadius: 8, fontWeight: 600, fontSize: "0.9375rem", cursor: "pointer", color: "var(--ink, #0e0e11)" }}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isUpdating}
                  style={{ flex: 2, padding: "0.625rem", background: isUpdating ? "#e5e7eb" : "var(--brand, #C1272D)", color: isUpdating ? "var(--text-3, #9ca3af)" : "#fff", border: "none", borderRadius: 8, fontWeight: 700, fontSize: "0.9375rem", cursor: isUpdating ? "default" : "pointer" }}
                >
                  {isUpdating ? "Saving…" : "Save Changes"}
                </button>
              </div>
            </div>
          </form>
        )}
      </div>
    </main>
  );
}
