"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";

const API_BASE = "";

export default function ProfilePage() {
  const {user, token, loading, logout, refreshUser} = useAuth();
  const router = useRouter();
  const petImageObjectUrlsRef = useRef([]);

  const [pets, setPets] = useState([]);
  const [loadingPets, setLoadingPets] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [editingPet, setEditingPet] = useState(null);
  const [petName, setPetName] = useState("");
  const [species, setSpecies] = useState("");
  const [breed, setBreed] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [petError, setPetError] = useState(null);
  const [profileForm, setProfileForm] = useState({ fullName: "", email: "", phone: "" });
  const [profileSubmitting, setProfileSubmitting] = useState(false);
  const [profileError, setProfileError] = useState(null);
  const [profileSuccess, setProfileSuccess] = useState(null);
  const [avatarSubmitting, setAvatarSubmitting] = useState(false);

  const clearPetImageObjectUrls = useCallback(() => {
    for (const objectUrl of petImageObjectUrlsRef.current) {
      URL.revokeObjectURL(objectUrl);
    }
    petImageObjectUrlsRef.current = [];
  }, []);

  useEffect(() => {
    if (!loading && !user) {
      router.replace(`/login?next=${encodeURIComponent("/profile")}`);
    }

  }, [user, loading, router]);

  useEffect(() => {
    setProfileForm({
      fullName: user?.fullName || "",
      email: user?.email || "",
      phone: user?.phone || "",
    });
  }, [user]);

  const loadPets = useCallback(async () => {
    if (!token) return;
    setLoadingPets(true);

    try {
      const response = await fetch(`${API_BASE}/api/v1/my-pets`, {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (!response.ok) {
        throw new Error(`Request failed (${response.status})`);
      }

      const petData = await response.json();
      clearPetImageObjectUrls();

      const petsWithResolvedImages = await Promise.all(
        (Array.isArray(petData) ? petData : []).map(async (pet) => {
          if (!pet.imageUrl) {
            return pet;
          }

          try {
            const imageResponse = await fetch(`${API_BASE}${pet.imageUrl}`, {
              headers: { Authorization: `Bearer ${token}` },
            });

            if (!imageResponse.ok) {
              return { ...pet, imageUrl: null };
            }

            const blob = await imageResponse.blob();
            const objectUrl = URL.createObjectURL(blob);
            petImageObjectUrlsRef.current.push(objectUrl);

            return { ...pet, imageUrl: objectUrl };
          } catch {
            return { ...pet, imageUrl: null };
          }
        })
      );

      setPets(petsWithResolvedImages);
    }

    catch {
    }

    finally {
      setLoadingPets(false);
    }
  }, [token, clearPetImageObjectUrls]);

  useEffect(() => {
    return () => {
      clearPetImageObjectUrls();
    };
  }, [clearPetImageObjectUrls]);

  useEffect(() => {
if (user?.role === "CUSTOMER" || user?.role === "ADMIN") {
      loadPets();
    }
  }, [user, loadPets]);

  function handleLogout() {
    logout();
    router.push("/");
  }

  async function handleProfileSubmit(e) {
    e.preventDefault();
    setProfileSubmitting(true);
    setProfileError(null);
    setProfileSuccess(null);

    try {
      const res = await fetch(`${API_BASE}/api/v1/auth/me`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(profileForm),
      });

      const data = await res.json().catch(() => null);
      if (!res.ok) {
        throw new Error(data?.message || `Request failed (${res.status})`);
      }

      await refreshUser();
      setProfileSuccess("Profile updated successfully.");
    }

    catch (err) {
      setProfileError(err.message);
    }

    finally {
      setProfileSubmitting(false);
    }
  }

  async function handleAvatarUpload(file) {
    if (!file) {
      return;
    }

    const formData = new FormData();
    formData.append("avatar", file);
    setAvatarSubmitting(true);
    setProfileError(null);
    setProfileSuccess(null);

    try {
      const res = await fetch(`${API_BASE}/api/v1/auth/me/avatar`, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });

      const data = await res.json().catch(() => null);
      if (!res.ok) {
        throw new Error(data?.message || "Failed to upload avatar");
      }

      await refreshUser();
      setProfileSuccess(data?.message || "Avatar updated successfully.");
    }

    catch (err) {
      setProfileError(err.message);
    }

    finally {
      setAvatarSubmitting(false);
    }
  }

  async function handleAvatarDelete() {
    setAvatarSubmitting(true);
    setProfileError(null);
    setProfileSuccess(null);

    try {
      const res = await fetch(`${API_BASE}/api/v1/auth/me/avatar`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` },
      });

      const data = await res.json().catch(() => null);
      if (!res.ok) {
        throw new Error(data?.message || "Failed to delete avatar");
      }

      await refreshUser();
      setProfileSuccess(data?.message || "Avatar removed successfully.");
    }

    catch (err) {
      setProfileError(err.message);
    }

    finally {
      setAvatarSubmitting(false);
    }
  }

  function openAddForm() {
    setEditingPet(null);
    setPetName("");
    setSpecies("");
    setBreed("");
    setPetError(null);
    setShowForm(true);
  }

  function openEditForm(pet) {
    setEditingPet(pet);
    setPetName(pet.petName);
    setSpecies(pet.species);
    setBreed(pet.breed || "");
    setPetError(null);
    setShowForm(true);
  }

  function closeForm() {
    setShowForm(false);
    setEditingPet(null);
    setPetError(null);
  }

  async function handlePetSubmit(e) {
    e.preventDefault();
    setPetError(null);
    setSubmitting(true);

    const url = editingPet
      ? `${API_BASE}/api/v1/my-pets/${editingPet.customerPetId}`
      : `${API_BASE}/api/v1/my-pets`;

    try {
      const res = await fetch(url, {
        method: editingPet ? "PUT" : "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ petName, species, breed: breed || null }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.message || `Request failed (${res.status})`);
      }

      closeForm();
      loadPets();
    } 
    
    catch (err) {
      setPetError(err.message);
    } 
    
    finally {
      setSubmitting(false);
    }
  }

  async function handleDeletePet(id) {
    if (!confirm("Remove this pet profile?")) {
      return;
    }

    try {
      await fetch(`${API_BASE}/api/v1/my-pets/${id}`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` },
      });
      loadPets();
    }
    
    catch {
    }
  }

  async function handleImageUpload(petId, file) {
    const formData = new FormData();
    formData.append("image", file);

    try {
      const res = await fetch(`${API_BASE}/api/v1/my-pets/${petId}/image`, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        alert(data?.message || "Failed to upload image");
        return;
      }

      loadPets();
    } 
    
    catch {
      alert("Failed to upload image");
    }
  }

  if (loading || !user) {
    return <main className="auth-page"><p className="profile-loading">Loading…</p></main>;
  }

  const fields = [
    {label: "Full Name", value: user.fullName},
    {label: "Username", value: user.username},
    {label: "Email", value: user.email},
    {label: "Phone", value: user.phone || "—"},
    {label: "Role", value: user.role},
    ...(user.storeName ? [{ label: "Store", value: user.storeName }] : []),
  ];

  return (
    <main className="profile-page-layout">
      <div className="profile-card">
        <div className="profile-avatar-circle">
          {user.avatarUrl ? (
            <img src={user.avatarUrl} alt={user.fullName || user.username} className="profile-avatar-image" />
          ) : (
            (user.fullName || user.username).charAt(0).toUpperCase()
          )}
        </div>

        <h1 className="profile-name">{user.fullName || user.username}</h1>
        <span className="profile-role-badge">{user.role}</span>

        <dl className="profile-fields">
          {fields.map(({ label, value }) => (
            <div key={label} className="profile-field-row">
              <dt className="profile-field-label">{label}</dt>
              <dd className="profile-field-value">{value}</dd>
            </div>
          ))}
        </dl>

        <form className="profile-update-form" onSubmit={handleProfileSubmit}>
          <h2 className="profile-update-title">Update Profile</h2>
          {profileError && <div className="appt-error">{profileError}</div>}
          {profileSuccess && <div className="appt-success">{profileSuccess}</div>}
          <label className="appt-label">
            Full Name
            <input
              className="appt-input"
              type="text"
              value={profileForm.fullName}
              onChange={(e) => setProfileForm((current) => ({ ...current, fullName: e.target.value }))}
              maxLength={100}
            />
          </label>
          <label className="appt-label">
            Email
            <input
              className="appt-input"
              type="email"
              value={profileForm.email}
              onChange={(e) => setProfileForm((current) => ({ ...current, email: e.target.value }))}
              required
            />
          </label>
          <label className="appt-label">
            Phone
            <input
              className="appt-input"
              type="text"
              value={profileForm.phone}
              onChange={(e) => setProfileForm((current) => ({ ...current, phone: e.target.value }))}
              maxLength={20}
            />
          </label>
          <div className="profile-avatar-actions">
            <label className="profile-avatar-upload-btn">
              <input
                type="file"
                accept="image/jpeg,image/png,image/gif"
                className="profile-pet-upload-input"
                onChange={(e) => {
                  handleAvatarUpload(e.target.files?.[0] || null);
                  e.target.value = "";
                }}
              />
              {avatarSubmitting ? "Working..." : user.avatarUrl ? "Change Avatar" : "Upload Avatar"}
            </label>
            {user.avatarUrl && (
              <button type="button" className="profile-pet-delete-btn" onClick={handleAvatarDelete} disabled={avatarSubmitting}>
                Remove Avatar
              </button>
            )}
          </div>
          <button type="submit" className="appt-submit-btn" disabled={profileSubmitting || avatarSubmitting}>
            {profileSubmitting ? "Saving..." : "Save Profile"}
          </button>
        </form>

        <button type="button" className="auth-submit-btn profile-logout-btn" onClick={handleLogout}>
          Log Out
        </button>
      </div>

{(user.role === "CUSTOMER" || user.role === "ADMIN") && (
        <div className="profile-pets-section">
          <div className="profile-pets-header">
            <h2 className="profile-pets-title">My Pets</h2>
            <button type="button" className="profile-pets-add-btn" onClick={openAddForm}>+ Add Pet</button>
          </div>

          {showForm && (
            <form className="profile-pet-form" onSubmit={handlePetSubmit}>
              <h3 className="profile-pet-form-title">
                {editingPet ? "Edit Pet" : "Add a New Pet"}
              </h3>
              {petError && <div className="appt-error">{petError}</div>}
              <label className="appt-label">
                Name
                <input
                  className="appt-input"
                  type="text"
                  value={petName}
                  onChange={(e) => setPetName(e.target.value)}
                  required
                  maxLength={50}
                />
              </label>
              <label className="appt-label">
                Species
                <input
                  className="appt-input"
                  type="text"
                  value={species}
                  onChange={(e) => setSpecies(e.target.value)}
                  required
                  maxLength={50}
                  placeholder="e.g. Dog, Cat, Bird"
                />
              </label>
              <label className="appt-label">
                Breed (optional)
                <input
                  className="appt-input"
                  type="text"
                  value={breed}
                  onChange={(e) => setBreed(e.target.value)}
                  maxLength={50}
                  placeholder="e.g. Golden Retriever"
                />
              </label>
              <div className="profile-pet-form-actions">
                <button type="submit" className="appt-submit-btn" disabled={submitting}>
                  {submitting ? "Saving..." : editingPet ? "Save Changes" : "Add Pet"}
                </button>
                <button type="button" className="profile-pet-cancel-btn" onClick={closeForm}>
                  Cancel
                </button>
              </div>
            </form>
          )}

          {loadingPets ? (
            <p className="appt-loading">Loading pets...</p>
          ) : pets.length === 0 && !showForm ? (
            <p className="profile-pets-empty">No pet profiles yet. Add your first pet above!</p>
          ) : (
            <div className="profile-pets-grid">
              {pets.map((pet) => (
                <div key={pet.customerPetId} className="profile-pet-card">
                  <div className="profile-pet-card-img-area">
                    {pet.imageUrl ? (
                      <img
                        src={pet.imageUrl}
                        alt={pet.petName}
                        className="profile-pet-card-img"
                      />
                    ) : (
                      <div className="profile-pet-card-placeholder">🐾</div>
                    )}
                    <label className="profile-pet-upload-label">
                      <input
                        type="file"
                        accept="image/jpeg,image/png,image/gif"
                        className="profile-pet-upload-input"
                        onChange={(e) => {
                          if (e.target.files[0]) handleImageUpload(pet.customerPetId, e.target.files[0]);
                          e.target.value = "";
                        }}
                      />
                      📷
                    </label>
                  </div>
                  <div className="profile-pet-card-info">
                    <span className="profile-pet-card-name">{pet.petName}</span>
                    <span className="profile-pet-card-detail">{pet.species}</span>
                    {pet.breed && <span className="profile-pet-card-detail">{pet.breed}</span>}
                  </div>
                  <div className="profile-pet-card-actions">
                     <button type="button" className="profile-pet-edit-btn" onClick={() => openEditForm(pet)}>Edit</button>
                     <button type="button" className="profile-pet-delete-btn" onClick={() => handleDeletePet(pet.customerPetId)}>Remove</button>
                   </div>
                 </div>
               ))}
            </div>
          )}
        </div>
      )}
    </main>
  );
}
