"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { UserRound } from "lucide-react";
import routes from "@/app/routes";
import MyAdsGrid from "@/components/profile/MyAdsGrid";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { fetchProfile } from "@/state/profile/profileSlice";

const SellerProfileView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { user } = useAppSelector((state) => state.auth);
  const { profile, status } = useAppSelector((state) => state.profile);
  const [activeTab, setActiveTab] = useState<"Contact Info" | "Ads">("Contact Info");
  const [mounted, setMounted] = useState(false);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  React.useEffect(() => {
    if (mounted && user && !profile && status !== "loading") {
      dispatch(fetchProfile());
    }
  }, [mounted, user?.id, user?._id, profile, status, dispatch]);

  const currentProfile = profile || user;

  if (!mounted || (status === "loading" && !currentProfile)) {
    return (
      <div className="bg-white min-h-screen">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-16 animate-pulse">
          <div className="h-4 w-20 bg-gray-200 rounded mb-4" />
          <div className="h-8 w-64 bg-gray-200 rounded mb-6" />
          <div className="h-5 w-28 bg-gray-200 rounded mb-3" />
          <div className="flex flex-col sm:flex-row sm:items-center gap-6 mb-8">
            <div className="w-[100px] h-[100px] rounded-full bg-gray-200 shrink-0" />
            <div className="flex flex-col gap-2">
              <div className="h-6 w-48 bg-gray-200 rounded" />
              <div className="h-4 w-32 bg-gray-200 rounded" />
              <div className="h-8 w-24 bg-gray-200 rounded mt-1" />
            </div>
          </div>
          <div className="h-10 w-48 bg-gray-200 rounded mb-6" />
          <div className="h-64 w-full bg-gray-100 rounded-lg" />
        </div>
      </div>
    );
  }

  const seller = {
    name: currentProfile
      ? `${currentProfile.firstName || ""} ${currentProfile.lastName || ""}`.trim() ||
        currentProfile.name ||
        currentProfile.username ||
        ""
      : "",
    username: currentProfile?.username || "",
    memberSince: currentProfile?.createdAt
      ? new Date(currentProfile.createdAt).toLocaleDateString("en-US", {
          month: "short",
          year: "numeric",
        })
      : "Member",
    lastOnline: "Online now",
    phoneNumber: currentProfile?.phone || "-",
    address: currentProfile?.address || "-",
    city: currentProfile?.city || "-",
    state: currentProfile?.state || "-",
    country: currentProfile?.country || "-",
    postcode:
      currentProfile?.postalCode ||
      currentProfile?.postcode ||
      "-",
    profileImage: currentProfile?.profileImage,
  };

  const contactRows = [
    { label: "Formatted Name", value: seller.username ? `${seller.name} (${seller.username})` : seller.name },
    { label: "Phone Number", value: seller.phoneNumber },
    { label: "Street Address", value: seller.address },
    { label: "City / Town", value: seller.city },
    { label: "State", value: seller.state },
    { label: "Postcode", value: seller.postcode },
    { label: "Country", value: seller.country },
  ];

  return (
    <div className="bg-white min-h-screen">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-10 pt-8 pb-16">
        <p className="text-[13px] text-[#6B7A99] mb-4">My Profile</p>

        <div className="flex items-baseline gap-2 mb-6">
          <h1 className="font-helvetica text-[24px] leading-[32px] font-medium text-[#000000]">{seller.name}</h1>
          <span className="font-helvetica text-[24px] leading-[32px] font-medium text-[#717680]">({seller.username})</span>
        </div>

        <p className="font-helvetica text-[16px] leading-[24px] font-normal text-[#000000] mb-3">Profile Photo</p>

        <div className="flex flex-col sm:flex-row sm:items-center gap-6 mb-8">
          <div className="w-[100px] h-[100px] rounded-full border-2 border-dashed border-gray-300 flex items-center justify-center shrink-0 overflow-hidden bg-gray-50">
            {seller.profileImage ? (
              <img
                src={seller.profileImage}
                alt={seller.name}
                className="w-full h-full object-cover"
              />
            ) : (
              <UserRound className="w-10 h-10 text-gray-300" strokeWidth={1.5} />
            )}
          </div>

          <div className="flex flex-col gap-2">
            <div>
              <p className="text-[20px] font-medium text-[#0B0F19]">{seller.name}</p>
              <p className="text-[12px] text-[#686262]">({seller.username})</p>
            </div>
            <div className="flex flex-wrap items-center gap-x-6 gap-y-1 text-[12px]">
              <span className="text-[#686262]">
                Member Since: <span className="text-[#0B0F19]">{seller.memberSince}</span>
              </span>
              <span className="text-[#686262]">
                Last Online: <span className="text-[#0B0F19]">{seller.lastOnline}</span>
              </span>
            </div>
            <button
              type="button"
              onClick={() => router.push(routes.editProfile)}
              className="mt-1 self-start px-4 py-1.5 text-[12px] font-medium text-[#2954E8] border border-[#2954E8] rounded-md hover:bg-[#EEF2FF] transition-colors"
            >
              Edit Profile
            </button>
          </div>
        </div>

        <div className="flex items-end gap-2 border-b border-[#F0EFEF] mb-6">
          {(["Contact Info", "Ads"] as const).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-4 py-2.5 -mb-px text-[16px] font-medium whitespace-nowrap rounded-t-md transition-colors ${
                activeTab === tab
                  ? "text-[#2954E8] border border-[#F0EFEF] border-b-white bg-white"
                  : "text-[#686262] border border-transparent hover:text-[#0B0F19]"
              }`}
            >
              {tab}
            </button>
          ))}
        </div>

        {activeTab === "Contact Info" ? (
          <div className="border border-[#F0EFEF] rounded-lg overflow-hidden">
            <div className="px-5 py-3 bg-white border-b border-[#F0EFEF]">
              <p className="text-[18px] font-medium text-[#0B0F19]">Contact Information</p>
            </div>
            {contactRows.map((row, i) => (
              <div
                key={row.label}
                className={`grid grid-cols-1 sm:grid-cols-[200px_1fr] gap-1 sm:gap-4 px-5 py-3 ${
                  i % 2 === 0 ? "bg-[#F7F8FA]" : "bg-white"
                }`}
              >
                <span className="text-[16px] text-[#6B7A99]">{row.label}</span>
                <span className="text-[16px] font-medium text-[#0B0F19]">{row.value}</span>
              </div>
            ))}
          </div>
        ) : (
          <MyAdsGrid limit={6} showViewAll />
        )}
      </div>
    </div>
  );
};

export default SellerProfileView;
