import React, { useEffect, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function Profile() {
  const [activeSection, setActiveSection] = useState("profileInfo");
  const [avatar, setAvatar] = useState(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isAvatarModalOpen, setIsAvatarModalOpen] = useState(false);
  const fileRef = useRef(null);

  useEffect(() => {
    const onResize = () => {
      if (window.innerWidth >= 768) setIsSidebarOpen(false);
    };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  const handleAvatarChange = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      setAvatar(ev.target.result);
      toast.success("Avatar updated!");
    };
    reader.readAsDataURL(f);
  };

  const SectionButton = ({ id, label, icon }) => (
    <button
      onClick={() => {
        setActiveSection(id);
        if (window.innerWidth < 768) setIsSidebarOpen(false);
      }}
      className={`flex items-center gap-3 w-full text-left px-4 py-3 rounded-lg mb-2 transition-all duration-150 ${
        activeSection === id
          ? "bg-gradient-to-r from-orange-500 to-amber-400 text-white shadow-md scale-[1.01]"
          : "hover:bg-orange-50 text-gray-800"
      }`}
    >
      {icon && <span className="text-lg">{icon}</span>}
      <span className="font-medium">{label}</span>
    </button>
  );

  const handleFormSubmit = (e, requiredFields = []) => {
    e.preventDefault();
    const missing = requiredFields.filter((name) => !e.target[name]?.value.trim());
    if (missing.length) return toast.error("Please fill all required fields!");
    toast.success("Saved successfully!");
  };

  const cardClass = "bg-white rounded-2xl shadow-md p-6 w-full overflow-hidden";
  const sidebarVariants = { hidden: { x: "-100%" }, visible: { x: 0 } };
  const contentVariants = { hidden: { opacity: 0, y: 12 }, visible: { opacity: 1, y: 0 }, exit: { opacity: 0, y: -8 } };

  return (
    <div className="min-h-screen bg-gradient-to-br from-orange-50 to-yellow-50 text-gray-900 flex flex-col">
      <ToastContainer position="top-right" autoClose={2000} />

      {/* ===== Topbar ===== */}
      <header className="flex items-center justify-between px-4 md:px-8 py-4 bg-gradient-to-r from-orange-500 to-amber-400 text-white shadow-lg z-40">
        <div className="flex items-center gap-4">
          <div className="relative">
            <button
              onClick={() => setIsAvatarModalOpen(true)}
              className="w-12 h-12 md:w-14 md:h-14 rounded-full overflow-hidden border-2 border-white shadow-lg bg-white flex items-center justify-center text-orange-500 font-bold hover:scale-105 transition-transform"
              aria-label="Change avatar"
            >
              {avatar ? <img src={avatar} alt="Avatar" className="w-full h-full object-cover" /> : <span className="text-lg">U</span>}
            </button>
            <button
              onClick={() => fileRef.current && fileRef.current.click()}
              title="Quick upload"
              className="absolute -right-1 -bottom-1 bg-white text-orange-500 rounded-full p-1 shadow-sm border border-gray-100 text-xs"
            >
              ✎
            </button>
            <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarChange} />
          </div>
          <div>
            <h1 className="text-xl md:text-2xl font-extrabold">Hello 👋</h1>
            <p className="text-sm opacity-90">Welcome back — manage your account</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <div className="hidden md:flex items-center gap-3">
            <button className="bg-white/20 px-3 py-2 rounded-md backdrop-blur-sm">Orders</button>
            <button className="bg-white px-3 py-2 rounded-md text-orange-600">Wishlist</button>
          </div>
          <button className="md:hidden text-white text-2xl p-1" onClick={() => setIsSidebarOpen((s) => !s)} aria-label="Toggle menu">☰</button>
        </div>
      </header>

      <div className="flex-1 flex overflow-hidden">
        {/* ===== Sidebar ===== */}
        <AnimatePresence>
          {(isSidebarOpen || (typeof window !== "undefined" && window.innerWidth >= 768)) && (
            <motion.aside
              initial={window.innerWidth >= 768 ? false : { x: "-100%" }}
              animate="visible"
              exit="hidden"
              variants={sidebarVariants}
              transition={{ type: "tween", duration: 0.22 }}
              className="md:sticky top-16 left-0 z-10 h-[calc(100vh-64px)] w-72 md:w-64 bg-white/95 backdrop-blur-sm border-r border-gray-200 p-5 overflow-y-auto shadow-xl md:shadow-none"
            >
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-lg font-bold text-orange-600">Account Menu</h3>
                  <p className="text-sm text-gray-500">Manage settings & payments</p>
                </div>
                <button className="md:hidden text-xl" onClick={() => setIsSidebarOpen(false)} aria-label="Close menu">✕</button>
              </div>

              {/* Sections */}
              <div className="mb-4">
                <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">Account Settings</h4>
                <SectionButton id="profileInfo" label="Profile Information" icon="👤" />
                <SectionButton id="manageAddress" label="Manage Address" icon="🏠" />
                <SectionButton id="panCard" label="PAN Card Information" icon="🪪" />
              </div>
              <div className="mb-4">
                <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">Payments</h4>
                <SectionButton id="giftCard" label="Gift Cards" icon="🎁" />
                <SectionButton id="savedUpi" label="Saved UPI" icon="💸" />
                <SectionButton id="savedCards" label="Saved Cards" icon="💳" />
              </div>
              <div className="mb-4">
                <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">My Stuff</h4>
                <SectionButton id="coupons" label="My Coupons" icon="🏷️" />
                <SectionButton id="reviews" label="My Reviews & Ratings" icon="⭐" />
                <SectionButton id="notifications" label="Notifications" icon="🔔" />
              </div>
              <div className="border-t pt-4 space-y-2">
                <SectionButton id="faq" label="FAQs" icon="❓" />
                <SectionButton id="logout" label="Logout" icon="↩️" />
              </div>

              {/* Deactivate & Delete */}
              <div className="mt-6 border-t pt-4 space-y-2">
                <button
                  className="w-full bg-yellow-100 text-yellow-700 py-2 rounded-md hover:bg-yellow-200 transition-colors"
                  onClick={() => toast.info("Account deactivated (demo)!")}
                >
                  Deactivate Account
                </button>
                <button
                  className="w-full bg-red-100 text-red-600 py-2 rounded-md hover:bg-red-200 transition-colors"
                  onClick={() => toast.error("Account deleted (demo)!")}
                >
                  Delete Account
                </button>
              </div>
            </motion.aside>
          )}
        </AnimatePresence>

        {/* Mobile overlay */}
        <AnimatePresence>
          {isSidebarOpen && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 0.35 }} exit={{ opacity: 0 }} className="fixed inset-0 bg-black z-40 md:hidden" onClick={() => setIsSidebarOpen(false)} />
          )}
        </AnimatePresence>

        {/* ===== Main Content ===== */}
        <main className="flex-1 p-4 md:p-8 overflow-auto">
          <AnimatePresence mode="wait">
            <motion.div key={activeSection} variants={contentVariants} initial="hidden" animate="visible" exit="exit" transition={{ duration: 0.25 }} className="max-w-3xl mx-auto">
              <div className={cardClass}>
                {/* Section header */}
                <div className="flex items-start justify-between gap-4 mb-4">
                  <div>
                    <h2 className="text-2xl md:text-3xl font-bold text-orange-600">
                      {activeSection === "profileInfo" && "Profile Information"}
                      {activeSection === "manageAddress" && "Manage Address"}
                      {activeSection === "panCard" && "PAN Card Information"}
                      {activeSection === "giftCard" && "Gift Cards"}
                      {activeSection === "savedUpi" && "Saved UPI"}
                      {activeSection === "savedCards" && "Saved Cards"}
                      {activeSection === "coupons" && "My Coupons"}
                      {activeSection === "reviews" && "My Reviews & Ratings"}
                      {activeSection === "notifications" && "Notifications"}
                      {activeSection === "faq" && "FAQs"}
                      {activeSection === "logout" && "Logout"}
                    </h2>
                    <p className="text-sm text-gray-600 mt-1">
                      {activeSection === "profileInfo" && "Update your name, email and personal details."}
                      {activeSection === "manageAddress" && "Add or edit delivery addresses."}
                      {activeSection === "panCard" && "Upload and verify your PAN details."}
                      {activeSection === "giftCard" && "Redeem gift cards here."}
                      {activeSection === "savedUpi" && "Manage your saved UPI IDs."}
                      {activeSection === "savedCards" && "Save and manage your cards securely."}
                      {activeSection === "coupons" && "Apply coupon codes to your account."}
                      {activeSection === "reviews" && "View or write product reviews."}
                      {activeSection === "notifications" && "Your account notifications."}
                      {activeSection === "faq" && "Frequently asked questions."}
                      {activeSection === "logout" && "Sign out from this device."}
                    </p>
                  </div>
                </div>

                {/* ===== Section Forms ===== */}
                {activeSection === "profileInfo" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["fullName", "email"])}>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <input name="fullName" className="p-3 border rounded-md w-full" placeholder="Full Name" required />
                      <input name="email" type="email" className="p-3 border rounded-md w-full" placeholder="Email Address" required />
                      <select name="gender" className="p-3 border rounded-md w-full md:col-span-2" required>
                        <option value="">Gender</option>
                        <option>Male</option>
                        <option>Female</option>
                        <option>Other</option>
                      </select>
                    </div>
                    <div className="flex flex-col md:flex-row gap-3">
                      <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md w-full md:w-auto">Save Changes</button>
                      <button type="button" className="border px-5 py-3 rounded-lg w-full md:w-auto" onClick={() => toast.info("Reset (demo)")}>Reset</button>
                    </div>
                  </form>
                )}

                {activeSection === "manageAddress" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["fullName", "mobile", "address", "city", "pincode"])}>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <input name="fullName" className="p-3 border rounded-md w-full" placeholder="Full Name" required />
                      <input name="mobile" className="p-3 border rounded-md w-full" placeholder="Mobile Number" required />
                      <textarea name="address" className="p-3 border rounded-md w-full md:col-span-2" placeholder="Address" required />
                      <input name="city" className="p-3 border rounded-md w-full" placeholder="City" required />
                      <input name="pincode" className="p-3 border rounded-md w-full" placeholder="Pincode" required />
                    </div>
                    <div className="flex flex-col md:flex-row gap-3">
                      <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md w-full md:w-auto">Save Address</button>
                      <button type="button" className="border px-5 py-3 rounded-lg w-full md:w-auto" onClick={() => toast.info("Add new address (demo)")}>Add New</button>
                    </div>
                  </form>
                )}

                {activeSection === "panCard" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["panNumber", "panName"])}>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <input name="panNumber" className="p-3 border rounded-md w-full" placeholder="PAN Card Number" required />
                      <input name="panName" className="p-3 border rounded-md w-full" placeholder="Full Name on PAN" required />
                    </div>
                    <div>
                      <label className="block text-sm text-gray-600 mb-2">Upload PAN Card (JPEG only)</label>
                      <input type="file" accept=".jpeg,.jpg" className="w-full" required />
                    </div>
                    <div className="flex items-center gap-2">
                      <input type="checkbox" required />
                      <span className="text-sm">I hereby declare that the above PAN information is correct.</span>
                    </div>
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Upload</button>
                  </form>
                )}

                {activeSection === "giftCard" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["giftCard"])}>
                    <input name="giftCard" className="p-3 border rounded-md w-full md:max-w-md" placeholder="Enter Gift Card Code" required />
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Redeem</button>
                  </form>
                )}

                {activeSection === "savedUpi" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["upiId"])}>
                    <input name="upiId" className="p-3 border rounded-md w-full md:max-w-md" placeholder="Enter UPI ID" required />
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Save</button>
                  </form>
                )}

                {activeSection === "savedCards" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["cardNumber", "cardName", "expiry"])}>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <input name="cardNumber" className="p-3 border rounded-md w-full" placeholder="Card Number" required />
                      <input name="cardName" className="p-3 border rounded-md w-full" placeholder="Cardholder Name" required />
                      <input name="expiry" type="month" className="p-3 border rounded-md w-full md:col-span-2" required />
                    </div>
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Save Card</button>
                  </form>
                )}

                {activeSection === "coupons" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["coupon"])}>
                    <input name="coupon" className="p-3 border rounded-md w-full md:max-w-md" placeholder="Enter Coupon Code" required />
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Apply</button>
                  </form>
                )}

                {activeSection === "reviews" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e, ["review"])}>
                    <textarea name="review" className="p-3 border rounded-md w-full" placeholder="Write your review" required />
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Submit Review</button>
                  </form>
                )}

                {activeSection === "notifications" && (
                  <form className="space-y-4" onSubmit={(e) => handleFormSubmit(e)}>
                    <div className="flex items-center gap-3">
                      <input type="checkbox" /> Email Notifications
                    </div>
                    <div className="flex items-center gap-3">
                      <input type="checkbox" /> SMS Notifications
                    </div>
                    <div className="flex items-center gap-3">
                      <input type="checkbox" /> Push Notifications
                    </div>
                    <button type="submit" className="bg-gradient-to-r from-orange-500 to-amber-400 text-white px-5 py-3 rounded-lg shadow-md">Save Preferences</button>
                  </form>
                )}

                {activeSection === "faq" && (
                  <div>
                    <h3 className="font-bold text-lg mb-2">Frequently Asked Questions</h3>
                    <p className="text-gray-600">1. How do I reset my password?</p>
                    <p className="text-gray-600">2. How do I redeem gift cards?</p>
                    <p className="text-gray-600">3. How do I update my PAN card?</p>
                  </div>
                )}

                {activeSection === "logout" && (
                  <div>
                    <button className="bg-red-500 text-white px-5 py-3 rounded-lg shadow-md" onClick={() => toast.info("Logged out (demo)!")}>Logout</button>
                  </div>
                )}
              </div>
            </motion.div>
          </AnimatePresence>
        </main>
      </div>

      {/* ===== Avatar Modal ===== */}
      <AnimatePresence>
        {isAvatarModalOpen && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div className="absolute inset-0 bg-black/40" onClick={() => setIsAvatarModalOpen(false)} />
            <motion.div initial={{ y: 16 }} animate={{ y: 0 }} exit={{ y: 16 }} transition={{ duration: 0.18 }} className="relative z-10 bg-white rounded-2xl shadow-xl p-6 w-full max-w-md">
              <h3 className="text-lg font-bold mb-2">Change Avatar</h3>  
              <input type="file" accept="image/*" onChange={(e) => { handleAvatarChange(e); setIsAvatarModalOpen(false); }} />
              <div className="mt-5 flex justify-end gap-3">
                <button className="px-4 py-2 rounded-md border" onClick={() => setIsAvatarModalOpen(false)}>Cancel</button>
                <button className="px-4 py-2 rounded-md bg-orange-500 text-white" onClick={() => { fileRef.current && fileRef.current.click(); setIsAvatarModalOpen(false); }}>Quick Upload</button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
