import React, { useMemo, useState } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import {
  ChevronLeft,
  Rocket,
  Clock3,
  Hand,
  Flame,
  PersonStanding,
  Ticket,
  Wallet,
  ChevronUp,
  Gift,
  ShieldCheck,
} from 'lucide-react';

const tabIcons = {
  progress: Rocket,
  coming: Clock3,
  finished: Hand,
};

function Header({ userInfo }) {
  return (
    <>
      <div className="relative flex h-[64px] items-center justify-center bg-[#045c5d] sm:h-[72px]">
        <button
          type="button"
          onClick={() => window.history.back()}
          className="absolute left-3 text-[#ffc61a] sm:left-4"
        >
          <ChevronLeft className="h-7 w-7 sm:h-8 sm:w-8" strokeWidth={2.4} />
        </button>

        <h1 className="text-[22px] font-bold text-[#ffc61a] sm:text-[26px]">
          Mission
        </h1>
      </div>

      <div className="relative overflow-hidden bg-[radial-gradient(circle_at_10%_25%,rgba(58,244,238,.55),transparent_18%),radial-gradient(circle_at_80%_15%,rgba(135,88,255,.45),transparent_18%),radial-gradient(circle_at_88%_78%,rgba(255,245,156,.35),transparent_15%),linear-gradient(90deg,#15e5ee_0%,#1b86db_38%,#4300bf_68%,#8f00d6_100%)] px-4 pb-8 pt-5 sm:px-6 sm:pb-10 sm:pt-6">
        <div className="pointer-events-none absolute inset-0">
          <div className="absolute left-[-20px] top-[70px] h-[120px] w-[60px] rounded-full bg-white/10 blur-md" />
          <div className="absolute right-[12px] top-[30px] h-[56px] w-[56px] rounded-full bg-white/10 blur-sm" />
          <div className="absolute left-[40%] top-[10px] h-[24px] w-[24px] rounded-full bg-white/20" />
        </div>

        <div className="relative z-10 flex items-center gap-3 sm:gap-4">
          <img
            src={userInfo.avatar}
            alt="avatar"
            className="h-[72px] w-[72px] rounded-full border-[4px] border-white object-cover shadow-lg sm:h-[84px] sm:w-[84px]"
          />

          <div className="min-w-0 text-white">
            <div className="truncate text-[20px] font-semibold leading-tight sm:text-[24px]">
              {userInfo.name}
            </div>
            <div className="mt-1 text-[24px] font-bold leading-none sm:text-[28px]">
              {userInfo.balance}
            </div>
            <div className="mt-2 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-[12px] font-medium backdrop-blur-sm sm:text-[13px]">
              <ShieldCheck className="h-4 w-4" />
              Active mission rewards
            </div>
          </div>
        </div>

        <div className="pointer-events-none absolute inset-x-0 bottom-0 h-[82px] rounded-t-[100%] bg-[#efeff4]" />
      </div>
    </>
  );
}

function StatusTabs({ tabs, status, onChange }) {
  return (
    <div className="mx-3 -mt-7 rounded-[18px] bg-white/90 p-2 shadow-[0_10px_25px_rgba(0,0,0,.08)] backdrop-blur-sm sm:mx-5">
      <div className="grid grid-cols-3 gap-1">
        {tabs.map((tab) => {
          const Icon = tabIcons[tab.key];
          const active = status === tab.key;

          return (
            <button
              key={tab.key}
              type="button"
              onClick={() => onChange(tab.key)}
              className={`flex h-[52px] items-center justify-center gap-2 rounded-[14px] px-2 text-[14px] font-semibold transition-all sm:h-[58px] sm:text-[16px] ${
                active
                  ? 'bg-[#fff1f1] text-[#ff2c2c] shadow-inner'
                  : 'text-[#686868] hover:bg-[#f6f6f8]'
              }`}
            >
              <Icon className={`h-4 w-4 sm:h-5 sm:w-5 ${active ? 'fill-current' : ''}`} strokeWidth={2.4} />
              <span className="truncate">{tab.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Medal({ type = 'gold' }) {
  if (type === 'silver' || type === 'disabled') {
    return (
      <div className="relative h-[66px] w-[66px] sm:h-[78px] sm:w-[78px]">
        <div className="absolute left-[14px] top-0 h-[16px] w-[12px] bg-[#777]" />
        <div className="absolute left-[28px] top-0 h-[16px] w-[12px] bg-[#b0b0b0]" />
        <div className="absolute left-[42px] top-0 h-[16px] w-[12px] bg-[#777]" />
        <div className="absolute left-[7px] top-[12px] h-[50px] w-[50px] rounded-full border-[5px] border-[#a8a8a8] bg-[radial-gradient(circle,#f1f1f1_0%,#a5a5a5_58%,#7b7b7b_100%)] sm:left-[10px] sm:top-[14px] sm:h-[58px] sm:w-[58px] sm:border-[6px]" />
      </div>
    );
  }

  return (
    <div className="relative h-[66px] w-[66px] sm:h-[78px] sm:w-[78px]">
      <div className="absolute left-[14px] top-0 h-[18px] w-[10px] bg-[#2c58da]" />
      <div className="absolute left-[27px] top-0 h-[18px] w-[10px] bg-[#f0c944]" />
      <div className="absolute left-[40px] top-0 h-[18px] w-[10px] bg-[#2c58da]" />
      <div className="absolute left-[7px] top-[12px] h-[50px] w-[50px] rounded-full border-[5px] border-[#e8a877] bg-[radial-gradient(circle,#fff7d9_0%,#d9a168_48%,#9a6130_100%)] sm:left-[10px] sm:top-[14px] sm:h-[58px] sm:w-[58px] sm:border-[6px]" />
    </div>
  );
}

function MissionCard({ mission, grey = false }) {
  return (
    <div
      className={`mx-3 mt-5 overflow-hidden rounded-[18px] border border-white/40 bg-gradient-to-br p-4 shadow-[0_10px_24px_rgba(0,0,0,.06)] sm:mx-5 sm:p-5 ${
        grey
          ? 'from-[#e7e7e7] to-[#d3d3d3]'
          : mission.medal_type === 'gold'
          ? 'from-[#dce8f9] to-[#b8cae7]'
          : mission.medal_type === 'silver'
          ? 'from-[#e3e3e3] to-[#d0d0d0]'
          : 'from-[#e6e6e6] to-[#d5d5d5]'
      }`}
    >
      <div className="flex flex-col gap-4 sm:flex-row sm:gap-4">
        <div className="flex items-start gap-3 sm:block sm:pt-1">
          <Medal type={grey ? 'silver' : mission.medal_type} />

          <div className="min-w-0 flex-1 sm:hidden">
            <h3 className="truncate text-[20px] font-bold text-[#4b4b4b]">
              {mission.title}
            </h3>
            <div className="mt-2 flex flex-wrap gap-2">
              <Link
                href={route('mission.leaderboard', mission.key)}
                className="rounded-full border border-[#9a9a9a] bg-white/60 px-3 py-1.5 text-[13px] font-medium text-[#686868]"
              >
                Leaderboard
              </Link>
              <Link
                href={route('mission.rules', mission.key)}
                className="rounded-full border border-[#9a9a9a] bg-white/60 px-3 py-1.5 text-[13px] font-medium text-[#686868]"
              >
                Rules
              </Link>
            </div>
          </div>
        </div>

        <div className="min-w-0 flex-1 text-[#5d5d5d]">
          <div className="hidden items-start justify-between gap-3 sm:flex">
            <h3 className="truncate text-[24px] font-bold">{mission.title}</h3>

            <div className="flex w-[132px] shrink-0 flex-col gap-3">
              <Link
                href={route('mission.leaderboard', mission.key)}
                className="rounded-full border border-[#9a9a9a] bg-white/50 px-3 py-[7px] text-center text-[15px] text-[#686868]"
              >
                Leaderboard
              </Link>

              <Link
                href={route('mission.rules', mission.key)}
                className="rounded-full border border-[#9a9a9a] bg-white/50 px-3 py-[7px] text-center text-[15px] text-[#686868]"
              >
                Rules
              </Link>
            </div>
          </div>

          <div className="mt-1 space-y-1.5 text-[14px] sm:text-[17px]">
            <div>
              Date : <span className="font-semibold">{mission.date_range}</span>
            </div>
            <div>
              Remaining : <span className="font-semibold">{mission.remaining}</span>
            </div>
            <div>
              Milestones :{' '}
              <span className="font-semibold">
                {mission.milestones_done}/{mission.milestones_total}
              </span>
            </div>
          </div>

          <div className="mt-4 flex items-center gap-3 sm:items-end sm:gap-4">
            <div className="text-[22px] font-bold text-[#444] sm:text-[24px]">
              {mission.progress_percent}
              <span className="text-[15px] sm:text-[18px]">%</span>
            </div>

            <div className="h-[12px] flex-1 rounded-full bg-white/80 sm:mb-[4px] sm:h-[15px]">
              <div
                className="h-full rounded-full bg-[#70b5ff]"
                style={{ width: `${mission.progress_percent}%` }}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function TaskCard({ task, muted = false, last = false }) {
  return (
    <div className="flex gap-3 sm:gap-4">
      <div className="flex w-[44px] shrink-0 flex-col items-center sm:w-[62px]">
        <div
          className={`mt-1 flex h-[38px] w-[38px] items-center justify-center rounded-full shadow-sm sm:mt-2 sm:h-[42px] sm:w-[42px] ${
            muted ? 'bg-[#dadada]' : 'bg-[#f4b84c]'
          }`}
        >
          <PersonStanding className="h-4 w-4 text-white sm:h-5 sm:w-5" />
        </div>

        {!last ? (
          <div className="mt-3 h-full min-h-[92px] w-[4px] rounded-full bg-[#d0d0d0]" />
        ) : null}
      </div>

      <div className="flex-1 rounded-[16px] bg-white px-4 py-4 shadow-[0_8px_20px_rgba(0,0,0,.04)]">
        <div className="flex flex-col gap-2 text-[#4f5764] sm:flex-row sm:items-center sm:justify-between">
          <div className="text-[18px] font-bold sm:text-[21px]">Valid bet:</div>
          <div className="text-[16px] font-semibold sm:text-[18px]">
            ৳ {task.current} / {task.target}
          </div>
        </div>

        <div className="my-4 h-px bg-[#e4e4e4]" />

        <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
          <div
            className={`inline-flex items-center gap-2 rounded-full px-3 py-[7px] text-[14px] sm:text-[16px] ${
              muted ? 'bg-[#ededed] text-[#666]' : 'bg-[#f1d0f2] text-[#5e5860]'
            }`}
          >
            <Ticket className={`h-4 w-4 ${muted ? 'text-[#b7b7b7]' : 'text-[#ef69ea]'}`} />
            <span>
              {task.reward_title} :{' '}
              <span className={muted ? '' : 'font-semibold text-[#f05ef0]'}>
                {task.reward_qty}
              </span>
            </span>
          </div>

          <div
            className={`inline-flex items-center gap-2 rounded-full px-3 py-[7px] text-[14px] sm:text-[16px] ${
              muted ? 'bg-[#ededed] text-[#666]' : 'bg-[#cde3f7] text-[#4f5964]'
            }`}
          >
            <Wallet className={`h-4 w-4 ${muted ? 'text-[#c2c2c2]' : 'text-[#36a0f2]'}`} />
            <span>
              Bonus :{' '}
              <span className={muted ? '' : 'font-semibold text-[#36a0f2]'}>
                ৳ {task.bonus}
              </span>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

function EmptyState({ title = 'No mission available' }) {
  return (
    <div className="mx-4 mt-8 rounded-[20px] bg-white px-6 py-12 text-center shadow-[0_10px_24px_rgba(0,0,0,.04)]">
      <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-[#f6f1ff]">
        <Gift className="h-8 w-8 text-[#8d62f3]" />
      </div>
      <p className="mt-4 text-[18px] font-semibold text-[#5b5b5b]">{title}</p>
    </div>
  );
}

export default function MissionIndex() {
  const { userInfo, tabs, status, missions } = usePage().props;
  const [expanded, setExpanded] = useState(false);

  const firstMission = missions?.[0] ?? null;
  const taskList = firstMission?.tasks ?? [];

  const visibleTasks = useMemo(() => {
    if (status !== 'progress' && status !== 'coming') return [];
    if (expanded) return taskList;
    return taskList.slice(0, 3);
  }, [expanded, taskList, status]);

  const changeStatus = (nextStatus) => {
    router.get(
      route('mission.index'),
      { status: nextStatus },
      {
        preserveState: true,
        preserveScroll: true,
        replace: true,
      }
    );
    setExpanded(false);
  };

  return (
    <>
      <Head title="Mission" />

      <div className="mx-auto min-h-screen max-w-[545px] bg-[#efeff4]">
        <Header userInfo={userInfo} />
        <StatusTabs tabs={tabs} status={status} onChange={changeStatus} />

        {status === 'progress' && firstMission && (
          <>
            <MissionCard mission={firstMission} />

            <div className="mx-4 mt-5 flex items-center gap-3 text-[#59606d] sm:mx-5">
              <Flame className="h-7 w-7 fill-[#ff9100] text-[#ff9100] sm:h-8 sm:w-8" />
              <h2 className="text-[20px] font-bold sm:text-[25px]">
                Incomplete milestones ({taskList.length})
              </h2>
            </div>

            <div className="space-y-4 px-3 pb-6 pt-4 sm:space-y-5 sm:px-4">
              {visibleTasks.map((task, index) => (
                <TaskCard
                  key={index}
                  task={task}
                  last={index === visibleTasks.length - 1}
                />
              ))}
            </div>

            {taskList.length > 3 && (
              <div className="pb-8 text-center">
                <button
                  type="button"
                  onClick={() => setExpanded((v) => !v)}
                  className="inline-flex h-[50px] w-[124px] items-center justify-center gap-2 rounded-full bg-[#bebec3] text-[16px] font-medium text-white sm:h-[56px] sm:w-[132px] sm:text-[18px]"
                >
                  <span>{expanded ? 'Hide' : 'More'}</span>
                  <ChevronUp className={`h-4 w-4 ${expanded ? '' : 'rotate-180'}`} />
                </button>
              </div>
            )}
          </>
        )}

        {status === 'coming' && firstMission && (
          <>
            <MissionCard mission={firstMission} grey />

            <div className="space-y-4 px-3 pb-6 pt-4 sm:space-y-5 sm:px-4">
              {visibleTasks.map((task, index) => (
                <TaskCard
                  key={index}
                  task={task}
                  muted
                  last={index === visibleTasks.length - 1}
                />
              ))}
            </div>

            {taskList.length > 3 && (
              <div className="pb-8 text-center">
                <button
                  type="button"
                  onClick={() => setExpanded((v) => !v)}
                  className="inline-flex h-[50px] w-[124px] items-center justify-center gap-2 rounded-full bg-[#bebec3] text-[16px] font-medium text-white sm:h-[56px] sm:w-[132px] sm:text-[18px]"
                >
                  <span>{expanded ? 'Hide' : 'More'}</span>
                  <ChevronUp className={`h-4 w-4 ${expanded ? '' : 'rotate-180'}`} />
                </button>
              </div>
            )}

            <div className="space-y-5 pb-6">
              {missions.slice(1).map((mission) => (
                <MissionCard key={mission.key} mission={mission} grey />
              ))}
            </div>
          </>
        )}

        {status === 'finished' && (
          <>
            {missions.length ? (
              <div className="space-y-5 pb-6 pt-5">
                {missions.map((mission) => (
                  <MissionCard key={mission.key} mission={mission} grey />
                ))}
              </div>
            ) : (
              <EmptyState title="No finished mission found" />
            )}
          </>
        )}
      </div>
    </>
  );
}