'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { Bell, BookOpen, Download, FileText, Medal, Search, Settings, Trophy, Users } from 'lucide-react';
import { dashboardApi } from '@/api/dashboardClient';
import AppNav from '@/components/liveclass/AppNav';

const BRAND = '#4A1429';
const GOLD = '#D4B038';
const BORDER = '#E5DDD5';

const CONFIG = {
  templates: { title: 'Business Templates', subtitle: 'Practical resources from the academy database.', entity: 'Template', icon: FileText },
  community: { title: 'Founder Community', subtitle: 'Questions, progress updates, and peer discussions.', entity: 'CommunityPost', icon: Users },
  certificates: { title: 'My Certificates', subtitle: 'Certificates earned from completed courses.', entity: 'Certificate', icon: Medal, personal: true },
  progress: { title: 'Learning Progress', subtitle: 'Your XP, streak, lessons, badges, and course progress.', entity: 'UserProgress', icon: Trophy, personal: true },
  notifications: { title: 'Notifications', subtitle: 'Course, community, and achievement updates.', entity: 'Notification', icon: Bell, personal: true },
  leaderboard: { title: 'Leaderboard', subtitle: 'Top founders ranked by XP.', entity: 'UserProgress', icon: Trophy },
  refer: { title: 'Referral Programme', subtitle: 'Track founders who joined through your referral.', entity: 'Referral', icon: Users, personal: true },
  journal: { title: 'Business Journal', subtitle: 'Your saved lesson notes and reflections.', entity: 'LessonProgress', icon: BookOpen, personal: true },
  settings: { title: 'Dashboard Settings', subtitle: 'Manage your Business Academy profile.', entity: null, icon: Settings },
  affiliate: { title: 'Affiliate Programme', subtitle: 'Apply to promote the academy and track your application.', entity: 'AffiliateApplication', icon: Users, personal: true },
  launch: { title: 'Launch Updates', subtitle: 'Join the list for upcoming academy launches.', entity: 'WaitlistEntry', icon: Bell, personal: true },
  blog: { title: 'Business Academy Blog', subtitle: 'Founder guides and academy updates.', entity: 'BlogPost', icon: FileText },
};

const belongsTo = (row, user) => String(row?.user_id ?? '') === String(user?.id ?? '')
  || String(row?.user_email || '').toLowerCase() === String(user?.email || '').toLowerCase()
  || String(row?.created_by || '').toLowerCase() === String(user?.email || '').toLowerCase();

function itemTitle(mode, item) {
  if (mode === 'templates') return item.title || item.name || 'Template';
  if (mode === 'community') return item.title || item.body?.slice(0, 70) || 'Community post';
  if (mode === 'certificates') return item.course_title || item.title || `Certificate ${item.id}`;
  if (mode === 'notifications') return item.title || 'Notification';
  if (mode === 'refer') return item.referred_name || item.referred_email || item.email || `Referral ${item.id}`;
  if (mode === 'journal') return item.notes_title || item.lesson_title || `Journal entry ${item.id}`;
  if (mode === 'blog') return item.title || `Article ${item.id}`;
  return item.display_name || item.user_name || item.full_name || `Founder ${item.user_id || item.id}`;
}

function itemDescription(mode, item) {
  if (mode === 'templates') return item.description || item.category || 'Downloadable academy resource';
  if (mode === 'community') return item.body || item.content || item.category;
  if (mode === 'certificates') return item.verification_code ? `Verification code: ${item.verification_code}` : item.status;
  if (mode === 'notifications') return item.body || item.message || item.type;
  if (mode === 'refer') return item.status || item.created_date;
  if (mode === 'journal') return item.notes || item.reflection || item.updated_date;
  if (mode === 'blog') return item.excerpt || item.summary || item.content?.slice(0, 180);
  return `${Number(item.total_xp || 0).toLocaleString()} XP · ${item.current_streak_days || 0} day streak`;
}

export default function DashboardDataPage({ mode }) {
  const config = CONFIG[mode];
  const Icon = config.icon;
  const [user, setUser] = useState(null);
  const [items, setItems] = useState([]);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [post, setPost] = useState({ title: '', body: '' });
  const [profile, setProfile] = useState({ full_name: '', bio: '' });
  const [application, setApplication] = useState({ website_or_linkedin: '', promotion_method: '' });
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setError('');
    try {
      const currentUser = await dashboardApi.auth.me();
      setUser(currentUser);
      setProfile({ full_name: currentUser.full_name || '', bio: currentUser.bio || '' });
      if (!config.entity) return;
      const rows = await dashboardApi.entities[config.entity].filter({}, mode === 'leaderboard' ? '-total_xp' : '-created_date', 200);
      setItems(config.personal ? (rows || []).filter((row) => belongsTo(row, currentUser)) : (rows || []));
    } catch (loadError) {
      if (loadError?.status === 401) return window.location.replace('/dashboard/login');
      setError(loadError?.message || `Unable to load ${config.title.toLowerCase()}.`);
    } finally {
      setLoading(false);
    }
  }, [config, mode]);

  useEffect(() => { load(); }, [load]);

  const filtered = useMemo(() => {
    const term = query.trim().toLowerCase();
    if (!term) return items;
    return items.filter((item) => JSON.stringify(item).toLowerCase().includes(term));
  }, [items, query]);

  const createPost = async (event) => {
    event.preventDefault();
    if (!post.title.trim() || !post.body.trim()) return;
    setSaving(true);
    try {
      const created = await dashboardApi.entities.CommunityPost.create({ ...post, user_id: user.id, user_name: user.full_name, category: 'Discussion' });
      setItems((current) => [created, ...current]);
      setPost({ title: '', body: '' });
    } catch (saveError) { setError(saveError.message); } finally { setSaving(false); }
  };

  const saveProfile = async (event) => {
    event.preventDefault();
    setSaving(true);
    try {
      const updated = await dashboardApi.auth.updateMe(profile);
      setUser(updated);
    } catch (saveError) { setError(saveError.message); } finally { setSaving(false); }
  };

  const markRead = async (item) => {
    if (mode !== 'notifications' || item.is_read) return;
    await dashboardApi.entities.Notification.update(item.id, { is_read: true });
    setItems((current) => current.map((row) => row.id === item.id ? { ...row, is_read: true } : row));
  };

  const submitApplication = async (event) => {
    event.preventDefault(); setSaving(true);
    try {
      const entity = mode === 'affiliate' ? 'AffiliateApplication' : 'WaitlistEntry';
      const payload = mode === 'affiliate'
        ? { ...application, name: user.full_name, email: user.email, user_id: user.id, created_by: user.email, status: 'pending' }
        : { email: user.email, name: user.full_name, user_id: user.id, created_by: user.email, status: 'waiting' };
      const created = await dashboardApi.entities[entity].create(payload); setItems((current) => [created, ...current]);
    } catch (saveError) { setError(saveError.message); } finally { setSaving(false); }
  };

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <AppNav />
      <main className="mx-auto max-w-7xl px-4 pb-16 pt-24 md:px-6">
        <header className="flex flex-col justify-between gap-5 md:flex-row md:items-end">
          <div className="flex items-start gap-4"><div className="rounded-2xl p-3 text-amber-300" style={{ backgroundColor: BRAND }}><Icon className="h-7 w-7" /></div><div><p className="text-xs font-black uppercase tracking-[0.2em]" style={{ color: GOLD }}>Business Academy</p><h1 className="mt-1 text-3xl font-black" style={{ color: BRAND }}>{config.title}</h1><p className="mt-2 text-sm text-stone-500">{config.subtitle}</p></div></div>
          {config.entity && <label className="flex items-center gap-3 rounded-2xl border bg-white px-4 py-3 md:w-80" style={{ borderColor: BORDER }}><Search className="h-5 w-5 text-stone-400" /><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search" className="w-full bg-transparent text-sm outline-none" /></label>}
        </header>
        {error && <div className="mt-6 rounded-xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-700">{error}</div>}

        {mode === 'community' && <form onSubmit={createPost} className="mt-8 rounded-2xl border bg-white p-5" style={{ borderColor: BORDER }}><h2 className="font-black" style={{ color: BRAND }}>Start a discussion</h2><input value={post.title} onChange={(event) => setPost({ ...post, title: event.target.value })} placeholder="Discussion title" className="mt-4 w-full rounded-xl border p-3 text-sm outline-none" style={{ borderColor: BORDER }} /><textarea value={post.body} onChange={(event) => setPost({ ...post, body: event.target.value })} placeholder="Share a question or update" rows={3} className="mt-3 w-full rounded-xl border p-3 text-sm outline-none" style={{ borderColor: BORDER }} /><button disabled={saving} className="mt-3 rounded-xl px-5 py-2.5 text-sm font-black text-white disabled:opacity-50" style={{ backgroundColor: BRAND }}>Publish</button></form>}
        {(mode === 'affiliate' || mode === 'launch') && <form onSubmit={submitApplication} className="mt-8 rounded-2xl border bg-white p-5" style={{ borderColor: BORDER }}><h2 className="font-black" style={{ color: BRAND }}>{mode === 'affiliate' ? 'Affiliate application' : 'Join the launch list'}</h2>{mode === 'affiliate' && <><input value={application.website_or_linkedin} onChange={(event) => setApplication({ ...application, website_or_linkedin: event.target.value })} placeholder="Website or LinkedIn" className="mt-4 w-full rounded-xl border p-3 text-sm outline-none" style={{ borderColor: BORDER }} /><textarea value={application.promotion_method} onChange={(event) => setApplication({ ...application, promotion_method: event.target.value })} placeholder="How will you promote the academy?" rows={3} className="mt-3 w-full rounded-xl border p-3 text-sm outline-none" style={{ borderColor: BORDER }} /></>}<button disabled={saving || items.length > 0} className="mt-4 rounded-xl px-5 py-2.5 text-sm font-black text-white disabled:opacity-50" style={{ backgroundColor: BRAND }}>{items.length ? 'Already submitted' : saving ? 'Submitting…' : 'Submit'}</button></form>}

        {mode === 'settings' ? <form onSubmit={saveProfile} className="mt-8 max-w-2xl rounded-2xl border bg-white p-6" style={{ borderColor: BORDER }}><label className="block text-xs font-black uppercase text-stone-500">Full name</label><input value={profile.full_name} onChange={(event) => setProfile({ ...profile, full_name: event.target.value })} className="mt-2 w-full rounded-xl border p-3 outline-none" style={{ borderColor: BORDER }} /><label className="mt-5 block text-xs font-black uppercase text-stone-500">Founder bio</label><textarea value={profile.bio} onChange={(event) => setProfile({ ...profile, bio: event.target.value })} rows={5} className="mt-2 w-full rounded-xl border p-3 outline-none" style={{ borderColor: BORDER }} /><button disabled={saving} className="mt-5 rounded-xl px-6 py-3 text-sm font-black text-white disabled:opacity-50" style={{ backgroundColor: BRAND }}>{saving ? 'Saving…' : 'Save profile'}</button></form> : loading ? <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">{[1,2,3].map((key) => <div key={key} className="h-40 animate-pulse rounded-2xl bg-white" />)}</div> : filtered.length === 0 ? <div className="mt-8 rounded-2xl border bg-white p-12 text-center" style={{ borderColor: BORDER }}><Icon className="mx-auto h-10 w-10 text-stone-300" /><h2 className="mt-4 font-black" style={{ color: BRAND }}>No records yet</h2><p className="mt-1 text-sm text-stone-500">This page is connected to the database and will show records when available.</p></div> : <div className={`mt-8 grid gap-4 ${mode === 'leaderboard' ? 'grid-cols-1' : 'sm:grid-cols-2 lg:grid-cols-3'}`}>{filtered.map((item, index) => <article key={item.id || index} onClick={() => markRead(item)} className="rounded-2xl border bg-white p-5 shadow-sm" style={{ borderColor: mode === 'notifications' && !item.is_read ? GOLD : BORDER }}><div className="flex items-start justify-between gap-3"><div><p className="text-xs font-black uppercase tracking-wide" style={{ color: GOLD }}>{mode === 'leaderboard' ? `#${index + 1}` : item.category || item.type || item.status || config.title}</p><h2 className="mt-2 font-black" style={{ color: BRAND }}>{itemTitle(mode, item)}</h2></div>{mode === 'templates' && (item.file_url || item.download_url) && <a href={item.file_url || item.download_url} download className="rounded-lg p-2 text-white" style={{ backgroundColor: BRAND }}><Download className="h-4 w-4" /></a>}</div><p className="mt-3 line-clamp-4 text-sm leading-6 text-stone-500">{itemDescription(mode, item)}</p>{mode === 'certificates' && <Link href={`/dashboard/course/${item.course_id}`} className="mt-4 inline-block text-xs font-black" style={{ color: BRAND }}>View course →</Link>}</article>)}</div>}
      </main>
    </div>
  );
}
