'use client';

import { Download, FileText, Paperclip, Plus } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react';
import { AdminShell } from '@/components/admin-shell';
import {
  ConfirmDialog,
  EmptyState,
  ErrorBanner,
  LoadingSkeleton,
  PageHeader,
  SearchFilterBar,
  StatusBadge,
} from '@/components/ui/admin-ui';
import {
  proxyFetch,
  toProxyAssetUrl,
  type AcademicOverviewPayload,
  type NoticeItem,
} from '@/lib/proxy-client';

export default function NoticesPage() {
  const [notices, setNotices] = useState<NoticeItem[]>([]);
  const [overview, setOverview] = useState<AcademicOverviewPayload | null>(null);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [banner, setBanner] = useState<{ kind: 'error' | 'success'; text: string } | null>(null);

  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [priority, setPriority] = useState<'LOW' | 'NORMAL' | 'HIGH' | 'URGENT'>('NORMAL');
  const [audienceType, setAudienceType] = useState<string>('INSTITUTION');
  const [targetRole, setTargetRole] = useState<'STUDENT' | 'TEACHER'>('STUDENT');
  const [targetId, setTargetId] = useState('');
  const [expiresAt, setExpiresAt] = useState('');
  const [attachmentFile, setAttachmentFile] = useState<File | null>(null);

  const [pendingAction, setPendingAction] = useState<{
    id: string;
    kind: 'publish' | 'unpublish' | 'archive';
    title: string;
  } | null>(null);

  const loadNotices = useCallback(async (st: string) => {
    const query = st ? `?status=${encodeURIComponent(st)}` : '';
    const res = await proxyFetch<NoticeItem[]>(`admin/notices${query}`);
    if (res.success) {
      setNotices(res.data);
    } else {
      setBanner({ kind: 'error', text: res.error.message });
    }
  }, []);

  useEffect(() => {
    let active = true;
    void Promise.all([
      proxyFetch<NoticeItem[]>('admin/notices'),
      proxyFetch<AcademicOverviewPayload>('admin/academics/overview'),
    ]).then(([nRes, aRes]) => {
      if (!active) return;
      if (nRes.success) setNotices(nRes.data);
      else setBanner({ kind: 'error', text: nRes.error.message });
      if (aRes.success) setOverview(aRes.data);
      setLoading(false);
    });
    return () => {
      active = false;
    };
  }, []);

  async function handleCreate(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBanner(null);
    if (attachmentFile && attachmentFile.size > 25 * 1024 * 1024) {
      setBanner({ kind: 'error', text: 'Attachment exceeds maximum allowed size of 25 MB.' });
      return;
    }
    setBusy(true);

    let res;
    if (attachmentFile) {
      const formData = new FormData();
      formData.append('title', title.trim());
      formData.append('body', body.trim());
      formData.append('priority', priority);
      formData.append('audienceType', audienceType);
      if (audienceType === 'ROLE') formData.append('targetRole', targetRole);
      if (audienceType === 'PROGRAM') formData.append('programId', targetId);
      if (audienceType === 'DEPARTMENT') formData.append('departmentId', targetId);
      if (audienceType === 'SESSION') formData.append('sessionId', targetId);
      if (audienceType === 'BATCH') formData.append('batchId', targetId);
      if (audienceType === 'SECTION') formData.append('sectionId', targetId);
      if (expiresAt) formData.append('expiresAtUtc', new Date(expiresAt).toISOString());
      formData.append('file', attachmentFile);

      res = await proxyFetch<NoticeItem>('admin/notices', {
        method: 'POST',
        body: formData,
      });
    } else {
      const payload: Record<string, unknown> = {
        title: title.trim(),
        body: body.trim(),
        priority,
        audienceType,
      };
      if (audienceType === 'ROLE') payload.targetRole = targetRole;
      if (audienceType === 'PROGRAM') payload.programId = targetId;
      if (audienceType === 'DEPARTMENT') payload.departmentId = targetId;
      if (audienceType === 'SESSION') payload.sessionId = targetId;
      if (audienceType === 'BATCH') payload.batchId = targetId;
      if (audienceType === 'SECTION') payload.sectionId = targetId;
      if (expiresAt) payload.expiresAtUtc = new Date(expiresAt).toISOString();

      res = await proxyFetch<NoticeItem>('admin/notices', {
        method: 'POST',
        body: JSON.stringify(payload),
      });
    }

    setBusy(false);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setTitle('');
    setBody('');
    setExpiresAt('');
    setAttachmentFile(null);
    setBanner({ kind: 'success', text: 'Notice created as DRAFT.' });
    await loadNotices(statusFilter);
  }

  async function handleDownloadAttachment(noticeId: string) {
    setBanner(null);
    const res = await proxyFetch<{ downloadUrl: string; filename?: string }>(
      `notices/${noticeId}/download`,
    );
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    const url = toProxyAssetUrl(res.data.downloadUrl);
    if (url) {
      window.open(url, '_blank', 'noopener,noreferrer');
    }
  }

  async function executeStatusChange() {
    if (!pendingAction) return;
    setBusy(true);
    const res = await proxyFetch<NoticeItem>(
      `admin/notices/${pendingAction.id}/${pendingAction.kind}`,
      { method: 'POST' },
    );
    setBusy(false);
    setPendingAction(null);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setBanner({ kind: 'success', text: `Notice updated (${res.data.status}).` });
    await loadNotices(statusFilter);
  }

  const filteredNotices = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return notices;
    return notices.filter(
      (n) => n.title.toLowerCase().includes(q) || n.body.toLowerCase().includes(q),
    );
  }, [notices, search]);

  const scopeOptions = useMemo(() => {
    if (!overview) return [];
    switch (audienceType) {
      case 'PROGRAM':
        return overview.programs.map((p) => ({ id: p.id, label: `${p.code} — ${p.name}` }));
      case 'DEPARTMENT':
        return overview.departments.map((d) => ({ id: d.id, label: `${d.code} — ${d.name}` }));
      case 'SESSION':
        return overview.sessions.map((s) => ({ id: s.id, label: s.code }));
      case 'BATCH':
        return overview.batches.map((b) => ({ id: b.id, label: `${b.code} — ${b.name}` }));
      case 'SECTION':
        return overview.sections.map((s) => ({ id: s.id, label: `${s.code} (${s.name})` }));
      default:
        return [];
    }
  }, [overview, audienceType]);

  return (
    <AdminShell>
      <div className="mx-auto max-w-6xl space-y-6">
        <PageHeader
          breadcrumbs={[{ label: 'Overview', href: '/' }, { label: 'Notices' }]}
          icon={<FileText className="h-6 w-6 text-slate-700" aria-hidden="true" />}
          title="Institutional Notice Board"
          description="Author, target, publish, and archive notices across institution, role, or academic cohorts."
        />

        {banner && <ErrorBanner kind={banner.kind} message={banner.text} />}

        <form
          onSubmit={(e) => void handleCreate(e)}
          className="space-y-3 rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-5"
        >
          <h2 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
            <Plus className="h-4 w-4" aria-hidden="true" />
            <span>Create Notice</span>
          </h2>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
            <input
              required
              placeholder="Notice title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="rounded-lg border border-slate-300 px-3 py-1.5 text-sm sm:col-span-2"
            />
            <select
              aria-label="Priority"
              value={priority}
              onChange={(e) => setPriority(e.target.value as 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT')}
              className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-sm"
            >
              <option value="LOW">LOW</option>
              <option value="NORMAL">NORMAL</option>
              <option value="HIGH">HIGH</option>
              <option value="URGENT">URGENT</option>
            </select>
          </div>
          <textarea
            required
            rows={3}
            placeholder="Notice body..."
            value={body}
            onChange={(e) => setBody(e.target.value)}
            className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
          />
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
            <select
              aria-label="Audience Type"
              value={audienceType}
              onChange={(e) => {
                setAudienceType(e.target.value);
                setTargetId('');
              }}
              className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-sm"
            >
              <option value="INSTITUTION">Institution-Wide</option>
              <option value="ROLE">Role (Student / Teacher)</option>
              <option value="PROGRAM">Program</option>
              <option value="DEPARTMENT">Department</option>
              <option value="SESSION">Academic Session</option>
              <option value="BATCH">Batch</option>
              <option value="SECTION">Section</option>
            </select>

            {audienceType === 'ROLE' ? (
              <select
                aria-label="Target Role"
                value={targetRole}
                onChange={(e) => setTargetRole(e.target.value as 'STUDENT' | 'TEACHER')}
                className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-sm"
              >
                <option value="STUDENT">STUDENT</option>
                <option value="TEACHER">TEACHER</option>
              </select>
            ) : scopeOptions.length > 0 ? (
              <select
                required
                aria-label="Target Scope"
                value={targetId}
                onChange={(e) => setTargetId(e.target.value)}
                className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-sm"
              >
                <option value="">Select target...</option>
                {scopeOptions.map((opt) => (
                  <option key={opt.id} value={opt.id}>
                    {opt.label}
                  </option>
                ))}
              </select>
            ) : (
              <div />
            )}

            <input
              aria-label="Optional expiry"
              type="datetime-local"
              value={expiresAt}
              onChange={(e) => setExpiresAt(e.target.value)}
              className="rounded-lg border border-slate-300 px-3 py-1.5 text-sm"
            />
          </div>
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-dashed border-slate-300 bg-slate-50 px-3 py-2 text-xs">
            <label className="flex cursor-pointer items-center gap-2 font-medium text-slate-700">
              <Paperclip className="h-4 w-4 text-slate-500" aria-hidden="true" />
              <span>Optional Attachment (PDF, Image, DOC, PPT — max 25 MB)</span>
              <input
                type="file"
                aria-label="Notice attachment"
                accept=".pdf,.png,.jpg,.jpeg,.webp,.doc,.docx,.ppt,.pptx"
                onChange={(e) => setAttachmentFile(e.target.files?.[0] ?? null)}
                className="sr-only"
              />
            </label>
            {attachmentFile && (
              <div className="flex items-center gap-2 text-slate-700">
                <span>
                  {attachmentFile.name} ({Math.max(1, Math.round(attachmentFile.size / 1024))} KB)
                </span>
                <button
                  type="button"
                  onClick={() => setAttachmentFile(null)}
                  className="rounded border border-slate-300 bg-white px-2 py-0.5 text-xs hover:bg-slate-100"
                >
                  Clear
                </button>
              </div>
            )}
          </div>
          <button
            type="submit"
            disabled={busy}
            className="rounded-lg bg-slate-900 px-4 py-2 text-xs font-medium text-white hover:bg-slate-800 disabled:opacity-60"
          >
            Save Notice Draft
          </button>
        </form>

        <SearchFilterBar
          searchValue={search}
          onSearchChange={setSearch}
          searchPlaceholder="Search notice title or content..."
        >
          <select
            aria-label="Filter by status"
            value={statusFilter}
            onChange={(e) => {
              const next = e.target.value;
              setStatusFilter(next);
              void loadNotices(next);
            }}
            className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm"
          >
            <option value="">All Statuses</option>
            <option value="DRAFT">DRAFT</option>
            <option value="PUBLISHED">PUBLISHED</option>
            <option value="ARCHIVED">ARCHIVED</option>
          </select>
        </SearchFilterBar>

        {loading ? (
          <LoadingSkeleton rows={4} />
        ) : filteredNotices.length === 0 ? (
          <EmptyState
            icon={<FileText className="h-8 w-8" aria-hidden="true" />}
            title="No Notices Found"
            description="Create a notice above or adjust your status filter."
          />
        ) : (
          <section className="overflow-hidden rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)]">
            <ul className="divide-y divide-slate-200">
              {filteredNotices.map((n) => (
                <li
                  key={n.id}
                  className="flex flex-wrap items-start justify-between gap-4 px-5 py-4 text-xs"
                >
                  <div className="max-w-2xl space-y-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="text-sm font-semibold text-slate-900">{n.title}</p>
                      <StatusBadge status={n.priority} />
                      <StatusBadge status={n.status} />
                      <span className="rounded bg-slate-100 px-2 py-0.5 text-slate-600">
                        {n.audienceType}
                        {n.targetRole ? `: ${n.targetRole}` : ''}
                      </span>
                    </div>
                    <p className="text-slate-600">{n.body}</p>
                    {n.attachmentFilename && (
                      <button
                        type="button"
                        onClick={() => void handleDownloadAttachment(n.id)}
                        className="mt-1 inline-flex items-center gap-1.5 rounded-md border border-slate-300 bg-slate-50 px-2.5 py-1 text-xs font-medium text-slate-700 hover:bg-slate-100"
                      >
                        <Download className="h-3.5 w-3.5" aria-hidden="true" />
                        <span>{n.attachmentFilename}</span>
                      </button>
                    )}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {n.status !== 'PUBLISHED' && n.status !== 'ARCHIVED' && (
                      <button
                        type="button"
                        onClick={() =>
                          setPendingAction({ id: n.id, kind: 'publish', title: n.title })
                        }
                        className="rounded-lg bg-emerald-700 px-3 py-1.5 font-medium text-white hover:bg-emerald-800"
                      >
                        Publish
                      </button>
                    )}
                    {n.status === 'PUBLISHED' && (
                      <button
                        type="button"
                        onClick={() =>
                          setPendingAction({ id: n.id, kind: 'unpublish', title: n.title })
                        }
                        className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50"
                      >
                        Unpublish
                      </button>
                    )}
                    {n.status !== 'ARCHIVED' && (
                      <button
                        type="button"
                        onClick={() =>
                          setPendingAction({ id: n.id, kind: 'archive', title: n.title })
                        }
                        className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50"
                      >
                        Archive
                      </button>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          </section>
        )}

        <ConfirmDialog
          open={pendingAction !== null}
          busy={busy}
          title={`Confirm Notice ${pendingAction?.kind ?? ''}`}
          message={`Proceed with ${pendingAction?.kind ?? ''} for "${pendingAction?.title ?? ''}"?`}
          confirmLabel="Confirm"
          onCancel={() => setPendingAction(null)}
          onConfirm={() => void executeStatusChange()}
        />
      </div>
    </AdminShell>
  );
}
