import { useState } from "react"
import {
  Award,
  BookOpen,
  CalendarDays,
  ChevronDown,
  Clock3,
  Edit3,
  Layers3,
  Lightbulb,
  LockKeyhole,
  Sparkles,
  Star,
  Trophy,
  Zap,
} from "lucide-react"
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
} from "recharts"

import profileImg from '../../../../public/assets/profile/profileImage.png'
import Image from "next/image";
import { useAuth } from "@/hooks/use-auth";
import { useRouter } from "next/navigation";

interface UserProfile {
  id: string;
  name: string;
  email: string;
  mobile: string;
  role: string;
  status: string;
  createdAt: string;
  registration: {
    registrationType: string;
    companyName: string | null;
    designation: string | null;
    division: string | null;
    district: string | null;
    upazila: string | null;
  } | null;
}


const portraits = {
  theresa:
    "https://images.unsplash.com/photo-1758600587815-b654d1405e83?auto=format&fit=crop&w=160&h=160&q=85",
  devon:
    "https://images.unsplash.com/photo-1758600588086-dc9d345fd01f?auto=format&fit=crop&w=160&h=160&q=85",
  jerome:
    "https://images.unsplash.com/photo-1758600588428-2cca8c96bfba?auto=format&fit=crop&w=160&h=160&q=85",
  courtney:
    "https://images.unsplash.com/photo-1758600433721-60ff3153f81a?auto=format&fit=crop&w=120&h=120&q=85",
  jacob:
    "https://images.unsplash.com/photo-1758600436089-0660fce3e7e5?auto=format&fit=crop&w=120&h=120&q=85",
  eleanor:
    "https://images.unsplash.com/photo-1758600435880-d7c0546a69d0?auto=format&fit=crop&w=120&h=120&q=85",
}

const weeklyActivity = [
  { day: "M", focus: 2.5, bonus: 0 },
  { day: "T", focus: 4.2, bonus: 0 },
  { day: "W", focus: 5.1, bonus: 0 },
  { day: "T", focus: 3.6, bonus: 0 },
  { day: "F", focus: 4.1, bonus: 4.2 },
  { day: "S", focus: 1.5, bonus: 0 },
  { day: "S", focus: 2.9, bonus: 0 },
]

const leaderboard = [
  {
    place: "4th",
    name: "Courtney Henry",
    points: "4,527",
    streak: "217 days",
    image: portraits.courtney,
  },
  {
    place: "5th",
    name: "Jacob Jones",
    points: "3,815",
    streak: "200 days",
    image: portraits.jacob,
  },
  {
    place: "6th",
    name: "Eleanor Pena",
    points: "3,748",
    streak: "129 days",
    image: portraits.eleanor,
  },
  {
    place: "7th",
    name: "Sarthak (You)",
    points: "3,627",
    streak: "100 days",
    you: true,
  },
]

const heatmap = [
  0, 0, 1, 0, 2, 0, 1, 0, 0, 0, 1, 2, 0, 0, 0, 3, 1, 0, 0, 0, 1, 2, 3, 0, 0, 2,
  4, 3, 1, 0, 0, 0, 3, 4, 3, 1, 0, 2, 3, 0, 0, 1, 2, 4, 4, 2, 1, 0, 0, 2, 4, 3,
  0, 0, 1, 2, 0, 0, 3, 4, 2, 1, 0, 1, 2, 3, 0, 0, 0, 3, 4, 2, 0, 1, 0, 0, 2, 3,
  4, 2, 0, 0, 1, 2, 3, 1, 0, 0, 2, 4, 3, 2, 0, 1, 0,
]



function Penguin({ className = "h-20 w-20" }: { className?: string }) {
  return (
    <svg viewBox="0 0 120 120" className={className} aria-hidden="true">
      <ellipse cx="60" cy="64" rx="36" ry="45" fill="#6337df" />
      <ellipse cx="60" cy="71" rx="26" ry="32" fill="white" />
      <path
        d="M38 43c9 7 15 5 22-2 8 7 14 9 23 1-3-14-12-23-23-23-10 0-19 9-22 24Z"
        fill="#fff"
      />
      <circle cx="49" cy="43" r="3.2" fill="#252536" />
      <circle cx="72" cy="43" r="3.2" fill="#252536" />
      <path d="m55 50 6-5 7 5-7 6-6-6Z" fill="#ffad24" />
      <path d="M25 60 9 50l10 25 9 2" fill="#6337df" />
      <path d="m94 61 15-13-7 27-10 3" fill="#6337df" />
      <ellipse
        cx="46"
        cy="108"
        rx="13"
        ry="5"
        fill="#ffad24"
        transform="rotate(-10 46 108)"
      />
      <ellipse
        cx="77"
        cy="108"
        rx="13"
        ry="5"
        fill="#ffad24"
        transform="rotate(10 77 108)"
      />
    </svg>
  )
}

function Avatar({
  src,
  name,
  className = "h-11 w-11",
}: {
  src?: string
  name: string
  className?: string
}) {
  return src ? (
    <img
      src={src}
      alt={name}
      className={`${className} rounded-full border-2 border-white object-cover shadow`}
    />
  ) : (
    <div
      className={`${className} grid place-items-center rounded-full border-2 border-white bg-gradient-to-br from-cyan-300 to-violet-600 text-xs font-bold text-white shadow`}
      aria-label={name}
    >
      SA
    </div>
  )
}

function ProfileHeader() {
    const { user, isAuthenticated, isLoading } = useAuth();
  
    const [loggingOut, setLoggingOut] = useState(false);
    const [error, setError] = useState("");
    const router = useRouter();
    const formatJoinedDate = (date?: string) => {
      if (!date) return "N/A";

      return new Date(date).toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour:"2-digit",
        minute: "2-digit",
        hour12: true,
        timeZone: "Asia/Dhaka",

      });
    };
  return (
    <section className="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-card">
      <div className="profile-cover h-32 bg-gradient-to-br from-violet-400 to-violet-700" />
      <div className="relative px-7 pb-7">
        <div className="-mt-15 mb-4 flex items-end justify-between gap-4">
          <div className="rounded-full bg-gradient-to-br from-violet-300 to-violet-500 p-1 shadow-lg">
            <Image className="h-30 w-30" src={profileImg.src} alt="profile image" width={200} height={200}></Image>
          </div>
          <button className="mb-1 flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-xs font-semibold text-slate-600 transition hover:border-violet-300 hover:text-violet-600">
            <Edit3 size={14} /> Edit profile
          </button>
        </div>
        <h1 className="text-xl font-bold text-slate-900">{user?.name}</h1>
          {<h2 className="text-gray-500 text-sm">
              {user?.role
                ?.split("_")
                .map(
                  (word) =>
                    word.charAt(0).toUpperCase() +
                    word.slice(1).toLowerCase()
                )
                .join(" ")}
            </h2>}
        <p className="mt-0.5 text-sm text-slate-500">{user?.email}</p>
        <p className="mt-0.5 text-sm text-slate-500">{user?.registration?.designation}</p>
        <div className="mt-3 flex flex-wrap gap-x-5 gap-y-2 text-xs font-medium text-slate-500">
          <span className="flex items-center gap-1.5">
            <CalendarDays size={14} className="text-slate-400" /> Joined : {formatJoinedDate(user?.createdAt)}
          </span>
          <span className="flex items-center gap-1.5">
            <Clock3 size={14} className="text-slate-400" /> Intermediate
          </span>
        </div>
        <p className="mt-3 text-xs leading-5 text-slate-500">
          Committed to learning and advancing neurological physiotherapy
          techniques to improve patients&apos; quality of life.
        </p>
      </div>
    </section>
  )
}

function Stats() {
  const cards = [
    { label: "Lessons Completed", value: "127", icon: BookOpen },
    { label: "Points", value: "1729", icon: Zap },
    { label: "Rank", value: "#8", icon: Trophy },
  ]
  return (
    <section className="grid grid-cols-1 gap-3 sm:grid-cols-3">
      {cards.map(({ label, value, icon: Icon }) => (
        <div
          key={label}
          className="group relative min-h-28 overflow-hidden rounded-xl bg-gradient-to-br from-[#a779f6] to-[#7950e8] p-5 text-white shadow-violet"
        >
          <Icon size={21} strokeWidth={2.4} />
          <p className="mt-3 text-xl font-bold">{value}</p>
          <p className="mt-1 text-[11px] font-medium text-white/75">{label}</p>
          <Icon
            size={76}
            strokeWidth={1.25}
            className="absolute -bottom-4 -right-3 text-white/15 transition-transform group-hover:-rotate-6 group-hover:scale-105"
          />
        </div>
      ))}
    </section>
  )
}

function Podium({
  place,
  name,
  points,
  image,
  first,
}: {
  place: number
  name: string
  points: string
  image: string
  first?: boolean
}) {
  return (
    <div
      className={`flex flex-1 flex-col items-center ${
        first ? "order-2" : place === 2 ? "order-1" : "order-3"
      }`}
    >
      <div className="relative mb-2">
        {first && (
          <Sparkles
            size={18}
            className="absolute -left-5 -top-3 fill-amber-300 text-amber-300"
          />
        )}
        <Avatar
          src={image}
          name={name}
          className={first ? "h-14 w-14" : "h-12 w-12"}
        />
        <span className="absolute -bottom-1 -right-1 grid h-5 w-5 place-items-center rounded-full bg-amber-400 text-[9px] font-bold text-white ring-2 ring-white">
          {place}
        </span>
      </div>
      <p className="text-[11px] font-semibold text-slate-700">{name}</p>
      <p className="mt-0.5 text-[10px] font-bold text-violet-500">{points} P</p>
      <div
        className={`podium-step mt-3 flex w-full items-center justify-center bg-gradient-to-b from-[#8c5af4] to-[#632ee2] text-3xl font-bold text-white shadow-violet ${
          first ? "h-40 rounded-t-xl" : "h-28 rounded-t-lg"
        }`}
      >
        {place}
      </div>
    </div>
  )
}

function Leaderboard() {
  const [period, setPeriod] = useState<"Weekly" | "All time">("Weekly")
  return (
    <section>
      <div className="mb-4">
        <h2 className="section-title">Leaderboard</h2>
        <p className="section-subtitle">
          See how you stack up against others! Compete for the top spot.
        </p>
      </div>
      <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-card sm:p-7">
        <div className="flex border-b border-slate-100">
          {(["Weekly", "All time"] as const).map((item) => (
            <button
              key={item}
              onClick={() => setPeriod(item)}
              className={`relative flex-1 pb-3 text-xs font-semibold transition ${
                period === item
                  ? "text-slate-800"
                  : "text-slate-400 hover:text-slate-600"
              }`}
            >
              {item}
              {period === item && (
                <span className="absolute inset-x-4 -bottom-px h-0.5 bg-violet-500" />
              )}
            </button>
          ))}
        </div>
        <div className="mx-auto mt-10 flex max-w-xl items-end px-2 sm:px-8">
          <Podium
            place={2}
            name="Theresa Webb"
            points="5,851"
            image={portraits.theresa}
          />
          <Podium
            place={1}
            name="Devon Lane"
            points="7,923"
            image={portraits.devon}
            first
          />
          <Podium
            place={3}
            name="Jerome Bell"
            points="4,719"
            image={portraits.jerome}
          />
        </div>
        <p className="my-5 text-center text-[10px] font-medium text-slate-500">
          You&apos;re #23 out of 1000 learners today!
        </p>
        <div className="overflow-x-auto">
          <div className="min-w-[470px]">
            <div className="grid grid-cols-[52px_1fr_80px_86px] px-3 py-2 text-[10px] font-medium text-slate-400">
              <span>Place</span>
              <span>Name</span>
              <span>Points</span>
              <span>Streak</span>
            </div>
            {leaderboard.map((person) => (
              <div
                key={person.place}
                className={`grid grid-cols-[52px_1fr_80px_86px] items-center rounded-lg px-3 py-2.5 text-xs ${
                  person.you ? "bg-violet-50" : ""
                }`}
              >
                <span className="font-medium text-emerald-500">
                  ↑ {person.place}
                </span>
                <span className="flex items-center gap-2.5 font-semibold text-slate-700">
                  <Avatar
                    src={person.image}
                    name={person.name}
                    className="h-7 w-7"
                  />
                  {person.name}
                </span>
                <span className="font-medium text-slate-600">
                  {person.points}
                </span>
                <span className="text-slate-500">{person.streak}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  )
}

function ProgressCard({
  icon,
  title,
  detail,
  progress,
}: {
  icon: React.ReactNode
  title: string
  detail: string
  progress: number
}) {
  return (
    <div className="flex items-center gap-4 rounded-xl border border-slate-100 bg-white p-5 shadow-card">
      <div className="grid h-14 w-14 shrink-0 place-items-center rounded-xl bg-violet-50">
        {icon}
      </div>
      <div className="min-w-0 flex-1">
        <div className="flex items-center justify-between gap-3">
          <h3 className="text-sm font-bold text-slate-800">{title}</h3>
          <span className="text-[10px] font-semibold text-slate-400">
            {progress}%
          </span>
        </div>
        <p className="mt-1 truncate text-[10px] text-slate-400">{detail}</p>
        <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-slate-100">
          <div
            className="h-full rounded-full bg-gradient-to-r from-emerald-400 to-teal-300"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>
    </div>
  )
}

function LearningProgress() {
  return (
    <section>
      <h2 className="section-title">Your Progress</h2>
      <p className="section-subtitle">
        Keep track of your learning journey! Here&apos;s your progress on
        quizzes and flashcards.
      </p>
      <div className="mt-4 grid gap-3 sm:grid-cols-2">
        <ProgressCard
          title="Quiz"
          detail="Completed: 6/10 questions"
          progress={60}
          icon={<Lightbulb className="text-amber-400" size={30} />}
        />
        <ProgressCard
          title="Flashcard"
          detail="Reviewed: 15/20 cards"
          progress={80}
          icon={<Layers3 className="text-violet-500" size={30} />}
        />
      </div>
    </section>
  )
}

function RewardsBanner() {
  return (
    <section className="relative overflow-hidden rounded-2xl bg-gradient-to-r from-[#9168ed] via-[#966cf2] to-[#7a4ce7] px-7 py-6 text-white shadow-violet">
      <div className="relative z-10 max-w-sm">
        <h2 className="text-lg font-bold">Earn Points &amp; Rewards!</h2>
        <p className="mt-2 text-xs leading-5 text-white/75">
          Stay motivated, earn points and unlock exclusive rewards as you learn!
        </p>
        <button className="mt-4 rounded-lg bg-white px-4 py-2 text-[11px] font-bold text-violet-600 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
          Continue learning
        </button>
      </div>
      <div className="absolute right-5 top-1/2 -translate-y-1/2">
        <Penguin className="h-36 w-36 drop-shadow-xl" />
      </div>
      <div className="absolute -bottom-14 left-1/3 h-40 w-40 rounded-full bg-white/5" />
      <Sparkles className="absolute right-40 top-6 text-yellow-300" size={18} />
    </section>
  )
}

function AchievementCard({
  title,
  subtitle,
  date,
  color,
}: {
  title: string
  subtitle: string
  date: string
  color: string
}) {
  return (
    <article className="rounded-xl border border-slate-100 bg-white p-5 text-center shadow-card transition hover:-translate-y-1 hover:shadow-lg">
      <h3 className="text-xs font-bold text-slate-800">{title}</h3>
      <p className="mt-1 text-[10px] text-slate-400">{subtitle}</p>
      <div className="relative mx-auto my-4 grid h-24 w-24 place-items-center">
        <div
          className={`absolute inset-2 rotate-45 rounded-3xl ${color} opacity-20`}
        />
        <div className={`absolute inset-4 rounded-full ${color} shadow-lg`} />
        <Award
          className="relative z-10 text-white"
          size={46}
          strokeWidth={1.7}
        />
        <span className="absolute bottom-1 z-20 rounded-full bg-white px-2 py-0.5 text-[9px] font-black text-amber-500 shadow">
          <Star size={9} fill="currentColor" />
        </span>
      </div>
      <p className="text-[9px] text-slate-400">{date}</p>
    </article>
  )
}

function Achievements() {
  return (
    <section>
      <h2 className="section-title">Achievement</h2>
      <p className="section-subtitle">
        Celebrate your achievements! Check out the badges you&apos;ve earned.
      </p>
      <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-3">
        <AchievementCard
          title="Quiz Master"
          subtitle="Complete 30 quizzes"
          date="Earned July 10, 2024"
          color="bg-violet-500"
        />
        <AchievementCard
          title="Flashcard Champion"
          subtitle="Review 50 flashcards"
          date="Earned July 5, 2024"
          color="bg-rose-500"
        />
        <AchievementCard
          title="Progress Tracker"
          subtitle="Achieve 2000 streaks"
          date="Earned July 12, 2024"
          color="bg-cyan-500"
        />
      </div>
    </section>
  )
}

function UpgradeCard() {
  return (
    <section className="rounded-2xl border border-slate-100 bg-white p-6 text-center shadow-card">
      <div className="mx-auto grid h-20 w-20 place-items-center rounded-full bg-violet-50">
        <Penguin className="h-16 w-16" />
      </div>
      <h2 className="mt-3 text-base font-bold text-slate-800">
        Upgrade to Premium
      </h2>
      <p className="mx-auto mt-2 max-w-[220px] text-xs leading-5 text-slate-400">
        Unlock exclusive content and features with Physiopedia Premium.
      </p>
      <button className="mt-5 w-full rounded-lg bg-[#7038df] py-2.5 text-xs font-bold text-white shadow-violet transition hover:bg-[#5f2cca]">
        Upgrade Now
      </button>
    </section>
  )
}

function ChartTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null
  const hours = payload.reduce(
    (total: number, item: { value: number }) => total + item.value,
    0,
  )
  return (
    <div className="rounded-lg border border-slate-100 bg-white px-3 py-2 text-xs shadow-lg">
      <p className="font-semibold text-slate-700">
        {label} · {hours.toFixed(1)}h
      </p>
    </div>
  )
}

function ActivityChart() {
  const [period, setPeriod] = useState("Weekly")
  return (
    <section className="rounded-2xl border border-slate-100 bg-white p-5 shadow-card">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h2 className="text-sm font-bold text-slate-800">Your Activity</h2>
          <p className="mt-3 text-[10px] text-slate-400">Today</p>
          <p className="text-xl font-bold text-slate-800">14h 32m</p>
        </div>
        <button
          onClick={() => setPeriod(period === "Weekly" ? "Daily" : "Weekly")}
          className="flex items-center gap-1 rounded-md border border-slate-100 px-2 py-1.5 text-[10px] font-medium text-slate-500"
        >
          {period} <ChevronDown size={11} />
        </button>
      </div>
      <div className="mt-4 h-48">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={weeklyActivity}
            margin={{ top: 6, right: 0, left: 0, bottom: 0 }}
            barCategoryGap="28%"
          >
            <CartesianGrid vertical={false} stroke="#f1f3f8" />
            <XAxis
              dataKey="day"
              axisLine={false}
              tickLine={false}
              tick={{ fill: "#a1a7b3", fontSize: 10 }}
            />
            <Tooltip
              content={<ChartTooltip />}
              cursor={{ fill: "rgba(124, 78, 230, .04)" }}
            />
            <Bar dataKey="focus" stackId="activity" radius={[4, 4, 0, 0]}>
              {weeklyActivity.map((_, index) => (
                <Cell key={index} fill={index === 4 ? "#7644e9" : "#edf0f3"} />
              ))}
            </Bar>
            <Bar
              dataKey="bonus"
              stackId="activity"
              fill="#39cbb1"
              radius={[4, 4, 0, 0]}
            />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </section>
  )
}

function ActivityHeatmap() {
  const [month, setMonth] = useState("Last 3 months")
  return (
    <section className="rounded-2xl border border-slate-100 bg-white p-5 shadow-card">
      <div className="flex items-center justify-between gap-2">
        <h2 className="text-sm font-bold text-slate-800">Your Activity</h2>
        <button
          onClick={() =>
            setMonth(
              month === "Last 3 months" ? "Last 6 months" : "Last 3 months",
            )
          }
          className="flex items-center gap-1 text-[10px] font-medium text-slate-400"
        >
          {month} <ChevronDown size={11} />
        </button>
      </div>
      <div className="mt-5 overflow-hidden">
        <div className="grid grid-flow-col grid-rows-7 gap-[5px]">
          {heatmap.map((value, index) => (
            <span
              key={index}
              title={`${value} learning sessions`}
              className={`aspect-square min-w-2 rounded-[2px] ${
                value === 0
                  ? "bg-slate-100"
                  : value === 1
                    ? "bg-emerald-100"
                    : value === 2
                      ? "bg-emerald-300"
                      : value === 3
                        ? "bg-emerald-500"
                        : "bg-emerald-700"
              }`}
            />
          ))}
        </div>
      </div>
      <div className="mt-4 flex items-center justify-end gap-1 text-[9px] text-slate-400">
        Less
        {[0, 1, 2, 3, 4].map((level) => (
          <span
            key={level}
            className={`h-2.5 w-2.5 rounded-[2px] ${
              [
                "bg-slate-100",
                "bg-emerald-100",
                "bg-emerald-300",
                "bg-emerald-500",
                "bg-emerald-700",
              ][level]
            }`}
          />
        ))}
        More
      </div>
    </section>
  )
}

export default function ProfileDashboard() {
  return (
    <main className="bg-[#fbfbfd]">
      <div className="mx-auto grid max-w-[1160px] items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px]">
        <div className="space-y-7">
          <ProfileHeader />
          <Stats />
          <Leaderboard />
          <LearningProgress />
          <RewardsBanner />
          <Achievements />
        </div>
        <aside className="space-y-5 lg:sticky lg:top-7">
          <UpgradeCard />
          <ActivityChart />
          <ActivityHeatmap />
          <div className="flex items-center justify-center gap-2 py-2 text-[10px] font-medium text-slate-400">
            <LockKeyhole size={11} /> Your activity is private
          </div>
        </aside>
      </div>
    </main>
  )
}
