'use client';

import { useEffect, useMemo, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import {
  ArrowRight,
  AudioLines,
  BookOpenCheck,
  ChevronDown,
  FilePenLine,
  Headphones,
  History,
  ImageIcon,
  LayoutGrid,
  LockKeyhole,
  LogOut,
  MessageCircleMore,
  RefreshCw,
  Sparkles,
  UnlockKeyhole,
} from 'lucide-react';
import LightHeaderLogo from '@/components/brand/LightHeaderLogo';
import { useAuth } from '@/lib/AuthContext';
import { getApiPath } from '@/lib/basePath';

const ICONS = {
  writing: FilePenLine,
  pronunciation: AudioLines,
  photo: ImageIcon,
  accent: Headphones,
  coach: MessageCircleMore,
};

const FILTER_LABELS = {
  all: 'All activity',
  'writing-analyser': 'Writing',
  'pronunciation-drill': 'Pronunciation',
  'photo-description': 'Photo',
  'practice-with-ella': 'Ella',
  'practice-with-emma': 'Emma',
  'practice-with-eva': 'Eva',
  'practice-with-ellie': 'Ellie',
};

function displayName(user) {
  return String(user?.full_name || user?.first_name || user?.email || 'Learner').trim();
}

function initials(user) {
  const source = displayName(user);
  return source
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join('') || 'CV';
}

function formatActivityDate(value, timeZone = 'UTC') {
  if (!value) return 'Date unavailable';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return 'Date unavailable';
  return new Intl.DateTimeFormat('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true,
    timeZone,
    timeZoneName: 'short',
  }).format(date);
}

function statusFor(tool) {
  if (tool.unlimited) {
    return { label: 'Unlimited', Icon: Sparkles, className: 'bg-[#EEE9FF] text-[#5D3B96]' };
  }
  if (tool.locked) {
    return { label: 'Locked', Icon: LockKeyhole, className: 'bg-[#FFF0F0] text-[#9C2830]' };
  }
  return { label: 'Available', Icon: UnlockKeyhole, className: 'bg-[#EAF8F1] text-[#16704D]' };
}

function ToolCard({ tool }) {
  const Icon = ICONS[tool.icon] || Sparkles;
  const status = statusFor(tool);
  const StatusIcon = status.Icon;
  const usageLabel = tool.unlimited
    ? 'No usage limit'
    : `${tool.remaining} of ${tool.limit} free ${tool.limit === 1 ? 'use' : 'uses'} remaining`;
  const actionHref = tool.locked ? '/pricing' : tool.href;
  const actionLabel = tool.locked ? 'Unlock more' : 'Open tool';

  return (
    <article className="group relative flex min-h-[318px] flex-col overflow-hidden rounded-[1.75rem] border border-[#E7DBD2] bg-white p-5 shadow-[0_12px_34px_rgba(65,24,42,0.06)] transition duration-300 hover:-translate-y-1 hover:border-[#D7B85A] hover:shadow-[0_22px_50px_rgba(65,24,42,0.12)] sm:p-6">
      <div className="pointer-events-none absolute -right-16 -top-16 h-40 w-40 rounded-full opacity-60 blur-3xl" style={{ backgroundColor: tool.softAccent }} />
      <div className="relative flex items-start justify-between gap-4">
        {tool.image ? (
          <div className="relative h-14 w-14 overflow-hidden rounded-2xl ring-4 ring-white shadow-md" style={{ backgroundColor: tool.softAccent }}>
            <Image src={tool.image} alt={`${tool.coach} AI coach`} fill sizes="56px" className="object-cover" />
          </div>
        ) : (
          <div className="flex h-14 w-14 items-center justify-center rounded-2xl" style={{ backgroundColor: tool.softAccent, color: tool.accent }}>
            <Icon className="h-6 w-6" aria-hidden="true" />
          </div>
        )}
        <span className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[11px] font-black ${status.className}`}>
          <StatusIcon className="h-3.5 w-3.5" aria-hidden="true" /> {status.label}
        </span>
      </div>

      <div className="relative mt-5 flex-1">
        <p className="text-[11px] font-extrabold uppercase tracking-[0.16em]" style={{ color: tool.accent }}>{tool.category}</p>
        <h2 className="mt-1.5 text-xl font-black leading-tight text-[#421125]">{tool.name}</h2>
        <p className="mt-3 text-sm leading-6 text-[#765D67]">{tool.description}</p>
      </div>

      <div className="relative mt-5">
        <div className="flex items-center justify-between gap-3 text-xs font-bold">
          <span className={tool.locked ? 'text-[#9C2830]' : 'text-[#715864]'}>{usageLabel}</span>
          {!tool.unlimited && <span className="text-[#9A7B88]">{tool.used}/{tool.limit}</span>}
        </div>
        {!tool.unlimited && (
          <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-[#EFE7E2]" aria-label={`${tool.progress}% of free allowance used`}>
            <div className="h-full rounded-full transition-all" style={{ width: `${tool.progress}%`, backgroundColor: tool.locked ? '#9C2830' : tool.accent }} />
          </div>
        )}
        <Link
          href={actionHref}
          className="mt-5 inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-black text-white transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#D4AF37] focus-visible:ring-offset-2"
          style={{ backgroundColor: tool.locked ? '#711F35' : tool.accent }}
        >
          {actionLabel} <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
        </Link>
      </div>
    </article>
  );
}

function StatCard({ icon: Icon, value, label }) {
  return (
    <div className="rounded-2xl border border-white/10 bg-white/[0.08] px-4 py-4 backdrop-blur-sm">
      <div className="flex items-center gap-3">
        <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-[#D4AF37]/15 text-[#F1CE62]">
          <Icon className="h-4 w-4" aria-hidden="true" />
        </span>
        <div>
          <p className="text-xl font-black text-white">{value}</p>
          <p className="text-xs font-semibold text-white/55">{label}</p>
        </div>
      </div>
    </div>
  );
}

function ActivityRow({ item, tool, timeZone }) {
  const Icon = ICONS[tool?.icon] || History;
  return (
    <li className="flex flex-col gap-4 border-b border-[#EEE4DE] px-5 py-5 last:border-b-0 sm:flex-row sm:items-center sm:px-6">
      <div className="flex min-w-0 flex-1 items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl" style={{ backgroundColor: tool?.softAccent || '#F4ECE8', color: tool?.accent || '#4A1429' }}>
          <Icon className="h-5 w-5" aria-hidden="true" />
        </span>
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-2">
            <p className="font-black text-[#421125]">{item.title}</p>
            <span className="rounded-full bg-[#F4EFEB] px-2.5 py-1 text-[10px] font-extrabold uppercase tracking-wide text-[#806874]">{item.kind}</span>
          </div>
          <p className="mt-1 line-clamp-2 text-sm leading-6 text-[#78616B]">{item.detail}</p>
          <p className="mt-1.5 text-xs font-semibold text-[#A08892]">{formatActivityDate(item.createdAt, timeZone)}</p>
        </div>
      </div>
      <div className="flex shrink-0 items-center justify-between gap-4 pl-[3.75rem] sm:pl-0">
        {item.score !== null && item.score !== undefined && (
          <span className="inline-flex h-12 min-w-12 items-center justify-center rounded-xl bg-[#FFF8DF] px-2 text-sm font-black text-[#8B6610]" aria-label={`Score ${Math.round(item.score)} out of 100`}>
            {Math.round(item.score)}
          </span>
        )}
        <Link href={item.href} className="inline-flex min-h-10 items-center gap-1.5 rounded-xl border border-[#DBC9D0] px-4 py-2 text-xs font-black text-[#5B1932] transition-colors hover:bg-[#F8EFF2]">
          Open <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
        </Link>
      </div>
    </li>
  );
}

export default function ToolsDashboardClient({ initialData, user }) {
  const { logout } = useAuth();
  const [data, setData] = useState(initialData);
  const [activeFilter, setActiveFilter] = useState('all');
  const [visibleCount, setVisibleCount] = useState(8);
  const [refreshing, setRefreshing] = useState(false);
  const [refreshError, setRefreshError] = useState('');
  const [activityTimeZone, setActivityTimeZone] = useState('UTC');

  useEffect(() => {
    const detected = Intl.DateTimeFormat().resolvedOptions().timeZone;
    if (!detected) return;
    try {
      new Intl.DateTimeFormat('en-GB', { timeZone: detected }).format();
      setActivityTimeZone(detected);
    } catch {
      // Keep the deterministic UTC fallback when the browser reports an invalid zone.
    }
  }, []);

  const toolMap = useMemo(() => Object.fromEntries(data.tools.map((tool) => [tool.key, tool])), [data.tools]);
  const filters = useMemo(() => {
    const present = new Set(data.history.map((item) => item.toolKey));
    return ['all', ...data.tools.map((tool) => tool.key).filter((key) => present.has(key))];
  }, [data.history, data.tools]);
  const filteredHistory = useMemo(
    () => activeFilter === 'all' ? data.history : data.history.filter((item) => item.toolKey === activeFilter),
    [activeFilter, data.history],
  );
  const visibleHistory = filteredHistory.slice(0, visibleCount);

  const refreshDashboard = async () => {
    if (refreshing) return;
    setRefreshing(true);
    setRefreshError('');
    try {
      const response = await fetch(getApiPath('/api/tools/dashboard'), { cache: 'no-store', credentials: 'same-origin' });
      const nextData = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(nextData?.message || 'Unable to refresh your dashboard.');
      setData(nextData);
      setVisibleCount(8);
    } catch (error) {
      setRefreshError(error?.message || 'Unable to refresh your dashboard.');
    } finally {
      setRefreshing(false);
    }
  };

  const chooseFilter = (key) => {
    setActiveFilter(key);
    setVisibleCount(8);
  };

  return (
    <main className="min-h-screen bg-[#F8F4F0] text-[#421125]">
      <header className="sticky top-0 z-40 border-b border-white/10 bg-[#3B0D20]/95 shadow-lg backdrop-blur-lg">
        <div className="mx-auto flex min-h-20 max-w-7xl items-center justify-between gap-4 px-4 sm:px-6 lg:px-8">
          <Link href="/" aria-label="Cambridge Veritas home"><LightHeaderLogo className="h-9 w-auto object-contain sm:h-10" /></Link>
          <nav className="flex items-center gap-2 sm:gap-3" aria-label="Tools dashboard navigation">
            <Link href="/tools" className="hidden min-h-10 items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold text-white/75 transition-colors hover:bg-white/10 hover:text-white sm:inline-flex">
              <LayoutGrid className="h-4 w-4" aria-hidden="true" /> Explore tools
            </Link>
            <div className="hidden items-center gap-2 rounded-xl bg-white/10 py-1.5 pl-2 pr-3 text-sm font-bold text-white md:flex">
              <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-[#D4AF37] text-xs font-black text-[#3B0D20]">{initials(user)}</span>
              <span className="max-w-36 truncate">{displayName(user)}</span>
            </div>
            <button type="button" onClick={() => logout('/')} className="inline-flex min-h-10 items-center gap-2 rounded-xl px-3 py-2 text-sm font-bold text-white/70 transition-colors hover:bg-white/10 hover:text-white" aria-label="Log out">
              <LogOut className="h-4 w-4" aria-hidden="true" /><span className="hidden sm:inline">Log out</span>
            </button>
          </nav>
        </div>
      </header>

      <div className="mx-auto max-w-7xl px-4 py-7 sm:px-6 sm:py-10 lg:px-8">
        <section className="relative overflow-hidden rounded-[2rem] bg-[linear-gradient(125deg,#51132E_0%,#721D3E_54%,#361020_100%)] px-6 py-8 shadow-[0_24px_60px_rgba(67,16,36,0.2)] sm:px-9 sm:py-10 lg:px-12">
          <div className="pointer-events-none absolute -right-20 -top-40 h-96 w-96 rounded-full bg-[#D4AF37]/20 blur-3xl" />
          <div className="pointer-events-none absolute inset-0 opacity-[0.07]" style={{ backgroundImage: 'radial-gradient(circle at 2px 2px, white 1px, transparent 0)', backgroundSize: '28px 28px' }} />
          <div className="relative grid gap-8 lg:grid-cols-[1fr_0.95fr] lg:items-end">
            <div>
              <span className="inline-flex items-center gap-2 rounded-full border border-[#E2C35B]/35 bg-[#D4AF37]/10 px-3 py-1.5 text-[11px] font-black uppercase tracking-[0.18em] text-[#F3D56D]">
                <Sparkles className="h-3.5 w-3.5" aria-hidden="true" /> Your learning workspace
              </span>
              <h1 className="mt-5 max-w-2xl text-3xl font-black leading-tight text-white sm:text-4xl lg:text-5xl">All your AI English tools, in one place.</h1>
              <p className="mt-4 max-w-2xl text-sm leading-7 text-white/65 sm:text-base">Continue a test, start a coaching conversation, and review your latest results without searching through separate pages.</p>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <StatCard icon={UnlockKeyhole} value={data.stats.availableTools} label="Tools available" />
              <StatCard icon={LockKeyhole} value={data.stats.lockedTools} label="Tools locked" />
              <StatCard icon={History} value={data.stats.totalActivities} label="Activities used" />
              <StatCard icon={BookOpenCheck} value={data.stats.recordedResults} label="Saved results" />
            </div>
          </div>
        </section>

        <section className="mt-9" aria-labelledby="tools-heading">
          <div className="mb-5 flex flex-col justify-between gap-3 sm:flex-row sm:items-end">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.17em] text-[#A27918]">Eight learning tools</p>
              <h2 id="tools-heading" className="mt-1 text-2xl font-black text-[#421125] sm:text-3xl">Choose what you want to practise</h2>
            </div>
            <button type="button" onClick={refreshDashboard} disabled={refreshing} className="inline-flex min-h-11 items-center justify-center gap-2 self-start rounded-xl border border-[#DCCDD2] bg-white px-4 py-2 text-sm font-black text-[#5B1932] shadow-sm transition-colors hover:bg-[#FBF4F6] disabled:cursor-wait disabled:opacity-60 sm:self-auto">
              <RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} aria-hidden="true" /> {refreshing ? 'Refreshing…' : 'Refresh access'}
            </button>
          </div>
          {refreshError && <p className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-700" role="alert">{refreshError}</p>}
          <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
            {data.tools.map((tool) => <ToolCard key={tool.key} tool={tool} />)}
          </div>
        </section>

        <section className="mt-12 pb-12" aria-labelledby="history-heading">
          <div className="flex flex-col justify-between gap-4 lg:flex-row lg:items-end">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.17em] text-[#A27918]">Practice history</p>
              <h2 id="history-heading" className="mt-1 text-2xl font-black text-[#421125] sm:text-3xl">Your latest activity</h2>
              <p className="mt-2 text-sm text-[#806874]">Results and successful coach conversations are saved here. Times follow your device timezone.</p>
            </div>
            {filters.length > 1 && (
              <div className="flex max-w-full gap-2 overflow-x-auto pb-1" role="tablist" aria-label="Filter activity by tool">
                {filters.map((key) => (
                  <button key={key} type="button" role="tab" aria-selected={activeFilter === key} onClick={() => chooseFilter(key)} className={`min-h-10 shrink-0 rounded-xl px-4 py-2 text-xs font-black transition-colors ${activeFilter === key ? 'bg-[#561630] text-white' : 'border border-[#DED1D5] bg-white text-[#725866] hover:bg-[#FBF4F6]'}`}>
                    {FILTER_LABELS[key] || toolMap[key]?.shortName || 'Tool'}
                  </button>
                ))}
              </div>
            )}
          </div>

          <div className="mt-5 overflow-hidden rounded-[1.75rem] border border-[#E7DBD2] bg-white shadow-[0_12px_34px_rgba(65,24,42,0.05)]">
            {visibleHistory.length ? (
              <ul>
                {visibleHistory.map((item) => <ActivityRow key={item.id} item={item} tool={toolMap[item.toolKey]} timeZone={activityTimeZone} />)}
              </ul>
            ) : (
              <div className="px-6 py-14 text-center">
                <span className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-[#F6EDF1] text-[#6B1D3B]"><History className="h-6 w-6" aria-hidden="true" /></span>
                <h3 className="mt-4 text-lg font-black text-[#421125]">No activity yet</h3>
                <p className="mx-auto mt-2 max-w-md text-sm leading-6 text-[#806874]">Open a tool and complete a test or coaching conversation. Your newest activity will appear here.</p>
                <Link href="/tools" className="mt-5 inline-flex min-h-11 items-center gap-2 rounded-xl bg-[#561630] px-5 py-2.5 text-sm font-black text-white">Explore tools <ArrowRight className="h-4 w-4" aria-hidden="true" /></Link>
              </div>
            )}
          </div>
          {visibleCount < filteredHistory.length && (
            <button type="button" onClick={() => setVisibleCount((count) => count + 8)} className="mx-auto mt-5 flex min-h-11 items-center gap-2 rounded-xl border border-[#DCCDD2] bg-white px-5 py-2.5 text-sm font-black text-[#5B1932] shadow-sm hover:bg-[#FBF4F6]">
              Show more <ChevronDown className="h-4 w-4" aria-hidden="true" />
            </button>
          )}
        </section>
      </div>
    </main>
  );
}
