'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Pathway = { id: number; title: string; difficulty: string; modules: number; hours: number; views: number };
type Resource = { id: number; title: string; type: string; category: string | null; difficulty: string | null; views: number };
type EventRow = { id: number; title: string; speaker: string | null; startsAt: string; timezone: string };

export default function LearnHubPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [pathways, setPathways] = useState<Pathway[]>([]);
  const [resources, setResources] = useState<Resource[]>([]);
  const [events, setEvents] = useState<EventRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [modal, setModal] = useState<'pathway' | 'resource' | 'event' | null>(null);
  const [saving, setSaving] = useState(false);

  const [pathwayForm, setPathwayForm] = useState({ title: '', difficulty: 'Beginner', modules: '1', hours: '1' });
  const [resourceForm, setResourceForm] = useState({ title: '', type: 'GUIDE', category: '' });
  const [eventForm, setEventForm] = useState({ title: '', speaker: '', startsAt: '' });

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [p, r, e] = await Promise.all([
        adminApiFetch('/admin/learn/pathways', accessToken, appSecretProof),
        adminApiFetch('/admin/learn/resources', accessToken, appSecretProof),
        adminApiFetch('/admin/learn/events', accessToken, appSecretProof),
      ]);
      setPathways(p.pathways || []); setResources(r.resources || []); setEvents(e.events || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submitPathway(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/learn/pathways', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ ...pathwayForm, modules: Number(pathwayForm.modules), hours: Number(pathwayForm.hours) }),
      });
      show('success', `"${pathwayForm.title}" pathway added.`);
      setPathwayForm({ title: '', difficulty: 'Beginner', modules: '1', hours: '1' });
      setModal(null);
      load();
    } catch { show('error', 'Could not add that pathway.'); }
    finally { setSaving(false); }
  }

  async function submitResource(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/learn/resources', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(resourceForm) });
      show('success', `"${resourceForm.title}" resource added.`);
      setResourceForm({ title: '', type: 'GUIDE', category: '' });
      setModal(null);
      load();
    } catch { show('error', 'Could not add that resource.'); }
    finally { setSaving(false); }
  }

  async function submitEvent(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/learn/events', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(eventForm) });
      show('success', `"${eventForm.title}" scheduled.`);
      setEventForm({ title: '', speaker: '', startsAt: '' });
      setModal(null);
      load();
    } catch { show('error', 'Could not schedule that event.'); }
    finally { setSaving(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h1 className="text-xl font-bold">Learn Hub &bull; Pathways &amp; Resources</h1>
        <button onClick={() => setModal('pathway')} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">+ Add Pathway</button>
      </div>

      {loading ? <TableSkeleton rows={3} cols={3} /> : (
        <div className="grid grid-cols-3 gap-4">
          {pathways.map((p) => (
            <div key={p.id} className="bg-white p-4 rounded-xl border border-brand-border transition-shadow hover:shadow-md">
              <p className="font-bold text-sm">{p.title}</p>
              <p className="text-xs text-gray-500 mt-1">{p.modules} modules &bull; {p.hours}h &bull; {p.difficulty} &bull; {p.views} views</p>
            </div>
          ))}
          {pathways.length === 0 && <p className="text-xs text-gray-400 col-span-3">No pathways yet.</p>}
        </div>
      )}

      <div className="bg-white rounded-xl border border-brand-border p-4">
        <div className="flex justify-between items-center mb-2">
          <p className="font-semibold text-sm">Resources</p>
          <button onClick={() => setModal('resource')} className="text-xs border px-3 py-1 rounded-full transition-colors hover:bg-brand-bg">+ Add Resource</button>
        </div>
        <div className="grid grid-cols-4 gap-3 text-xs">
          {resources.map((r) => (
            <div key={r.id} className="border border-brand-border rounded-lg p-2 transition-shadow hover:shadow-sm">
              <div className="bg-gray-100 h-20 rounded mb-2" />
              <p className="font-semibold">{r.title} &bull; {r.type} &bull; {r.difficulty || '—'}</p>
            </div>
          ))}
          {resources.length === 0 && <p className="text-gray-400 col-span-4">No resources yet.</p>}
        </div>
      </div>

      <div className="bg-white p-4 rounded-xl border border-brand-border">
        <div className="flex justify-between items-center mb-2">
          <p className="font-semibold text-sm">Live Academy &amp; Workshops</p>
          <button onClick={() => setModal('event')} className="text-xs border px-3 py-1 rounded-full transition-colors hover:bg-brand-bg">+ Schedule Event</button>
        </div>
        {events.map((e) => (
          <p key={e.id} className="text-xs mt-1">{e.title} &bull; {e.speaker || '—'} &bull; {new Date(e.startsAt).toLocaleString()} ({e.timezone})</p>
        ))}
        {events.length === 0 && <p className="text-xs text-gray-400 mt-1">No upcoming events.</p>}
      </div>

      {modal === 'pathway' && (
        <Modal title="Add Pathway" onClose={() => setModal(null)}>
          <form onSubmit={submitPathway} className="space-y-3">
            <input required autoFocus placeholder="Title" value={pathwayForm.title} onChange={(e) => setPathwayForm({ ...pathwayForm, title: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <select value={pathwayForm.difficulty} onChange={(e) => setPathwayForm({ ...pathwayForm, difficulty: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              <option>Beginner</option><option>Intermediate</option><option>Advanced</option>
            </select>
            <div className="grid grid-cols-2 gap-2">
              <input required type="number" min={1} placeholder="Modules" value={pathwayForm.modules} onChange={(e) => setPathwayForm({ ...pathwayForm, modules: e.target.value })}
                className="border border-brand-border rounded-lg px-3 py-2 text-sm" />
              <input required type="number" min={1} placeholder="Hours" value={pathwayForm.hours} onChange={(e) => setPathwayForm({ ...pathwayForm, hours: e.target.value })}
                className="border border-brand-border rounded-lg px-3 py-2 text-sm" />
            </div>
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Add Pathway'}</button>
          </form>
        </Modal>
      )}

      {modal === 'resource' && (
        <Modal title="Add Resource" onClose={() => setModal(null)}>
          <form onSubmit={submitResource} className="space-y-3">
            <input required autoFocus placeholder="Title" value={resourceForm.title} onChange={(e) => setResourceForm({ ...resourceForm, title: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <select value={resourceForm.type} onChange={(e) => setResourceForm({ ...resourceForm, type: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              <option value="VIDEO">Video</option><option value="PDF">PDF</option><option value="CASE_STUDY">Case Study</option><option value="GUIDE">Guide</option>
            </select>
            <input placeholder="Category (optional)" value={resourceForm.category} onChange={(e) => setResourceForm({ ...resourceForm, category: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Add Resource'}</button>
          </form>
        </Modal>
      )}

      {modal === 'event' && (
        <Modal title="Schedule Event" onClose={() => setModal(null)}>
          <form onSubmit={submitEvent} className="space-y-3">
            <input required autoFocus placeholder="Title" value={eventForm.title} onChange={(e) => setEventForm({ ...eventForm, title: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input placeholder="Speaker (optional)" value={eventForm.speaker} onChange={(e) => setEventForm({ ...eventForm, speaker: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input required type="datetime-local" value={eventForm.startsAt} onChange={(e) => setEventForm({ ...eventForm, startsAt: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">{saving ? 'Scheduling…' : 'Schedule Event'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
