'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth-context';
import { DepartmentPicker } from '@/components/pickers';
import { IconTrash } from '@/components/ui';
import { Pagination } from '@/components/data-table';
import { FloatInput, FloatSelect, FloatArea } from '@/components/float';
import { DatePicker } from '@/components/date-picker';
import { formatDate } from '@/lib/format';
import { validate, v, Errors } from '@/lib/validation';
import { useDialog } from '@/components/dialog';

const PRIO: Record<string, string> = {
  Low: 'bg-slate-100', Normal: 'bg-blue-100 text-blue-800',
  High: 'bg-amber-100 text-amber-800', Urgent: 'bg-red-100 text-red-800',
};
const PRIO_BAR: Record<string, string> = {
  Low: '#94a3b8', Normal: '#3b82f6', High: '#f59e0b', Urgent: '#ef4444',
};

function CreateNotice({ onDone }: { onDone: () => void }) {
  const { notify } = useDialog();
  const [form, setForm] = useState({ title: '', body: '', priority: 'Normal', audience: 'all', expires_at: '' });
  const [dept, setDept] = useState<number | null>(null);
  const [errs, setErrs] = useState<Errors>({});
  return (
    <form className="card space-y-2" noValidate onSubmit={async (e) => {
      e.preventDefault();
      const fe = validate({
        title: () => v.minLen(form.title, 3, 'Title'),
        body: () => v.minLen(form.body, 10, 'Body'),
        expires_at: () => v.optionalDate(form.expires_at, 'Expiry date'),
      });
      setErrs(fe);
      if (Object.keys(fe).length) return;
      try {
        await api.post('/api/v1/announcements', {
          ...form, department_id: dept, expires_at: form.expires_at || null,
        });
        notify('Notice published.', { tone: 'success' });
        onDone();
      } catch (ex: any) { notify(ex.message, { tone: 'error' }); }
    }}>
      <div className="grid md:grid-cols-2 gap-2">
        <FloatInput label="Title" id="nc-title" required error={errs.title} value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
        <div className="grid grid-cols-3 gap-2">
          <FloatSelect label="Priority" id="nc-priority" value={form.priority} onChange={(e) => setForm({ ...form, priority: e.target.value })}>
            <option>Low</option><option>Normal</option><option>High</option><option>Urgent</option>
          </FloatSelect>
          <FloatSelect label="Audience" id="nc-audience" value={form.audience} onChange={(e) => setForm({ ...form, audience: e.target.value })}>
            <option value="all">Everyone</option><option value="admins">Admins</option>
            <option value="stakeholders">Stakeholders</option><option value="employees">Employees</option>
          </FloatSelect>
          <DatePicker label="Expires" id="nc-expires" error={errs.expires_at} value={form.expires_at} onChange={(val) => setForm({ ...form, expires_at: val })} />
        </div>
      </div>
      <FloatArea label="Notice body (min 10 chars)" id="nc-body" rows={3} required error={errs.body} value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })} />
      <div className="flex gap-2 items-end">
        <div className="w-56"><DepartmentPicker value={dept} onChange={setDept} /></div>
        <button className="btn-primary text-sm btn-tall">Publish notice</button>
      </div>
    </form>
  );
}

const PAGE_SIZE = 10;

export default function AnnouncementsPage() {
  const { user } = useAuth();
  const { confirmDialog, notify } = useDialog();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const q = useQuery({ queryKey: ['announcements', page, search], queryFn: () => api.get(`/api/v1/announcements?search=${encodeURIComponent(search)}&page=${page}&limit=${PAGE_SIZE}`) });
  const [show, setShow] = useState(false);
  const [open, setOpen] = useState<number | null>(null);
  const canPost = user?.role !== 'employee';
  const markRead = async (id: number) => {
    setOpen(open === id ? null : id);
    await api.post(`/api/v1/announcements/${id}/read`);
    q.refetch();
  };
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap gap-2 items-center">
        <h1 className="page-title mr-auto">Notices {q.data?.unread ? <span className="badge bg-red-100 text-red-800">{q.data.unread} unread</span> : null}</h1>
        <input className="input max-w-52 text-sm" type="search" placeholder="Search notices" aria-label="Search notices" value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
        {canPost && <button className="btn-primary text-sm" onClick={() => setShow(v => !v)}>+ New Notice</button>}
      </div>
      {show && <CreateNotice onDone={() => { setShow(false); q.refetch(); }} />}
      {(q.data?.data ?? []).map((a: any) => (
        <div key={a.id} className={`card relative overflow-hidden ${a.is_read ? 'opacity-80' : ''}`}>
          <div className="absolute inset-y-0 left-0 w-1" style={{ background: PRIO_BAR[a.priority] ?? '#94a3b8' }} />
          <div className="flex flex-wrap gap-2 items-center pl-2">
            <button className="flex-1 min-w-0 text-left" onClick={() => markRead(a.id)} aria-expanded={open === a.id}>
              <span className="flex flex-wrap gap-2 items-center">
                <b className="text-[15px]">{a.title}</b>
                <span className={`badge ${PRIO[a.priority] ?? 'bg-slate-100'}`}>{a.priority}</span>
                {!a.is_read && <span className="badge bg-blue-600 text-white">new</span>}
              </span>
              <span className="block text-xs mt-0.5" style={{ color: 'var(--muted)' }}>
                {a.author_name ?? ''} · {a.department_name ?? 'All departments'} · {a.expires_at ? `expires ${formatDate(a.expires_at)}` : 'no expiry'}
              </span>
            </button>
            {(user?.role === 'admin' || user?.role === 'super_admin') && (
              <button type="button" className="btn-plain shrink-0" aria-label={`Delete notice ${a.title}`} title="Delete notice" onClick={async () => {
                if (!await confirmDialog('Delete this notice?', { title: 'Delete notice', confirmLabel: 'Delete' })) return;
                try { await api.del(`/api/v1/announcements/${a.id}`); notify('Notice deleted.', { tone: 'success' }); q.refetch(); }
                catch (e: any) { notify(e.message, { tone: 'error' }); }
              }}><IconTrash /></button>
            )}
          </div>
          {open === a.id && (
            <div className="mt-2 ml-2 text-sm whitespace-pre-wrap border-t pt-2">
              {a.body}
            </div>
          )}
        </div>
      ))}
      {!q.data?.data?.length && <p className="text-sm text-slate-500">{q.isLoading ? 'Loading…' : 'No notices.'}</p>}
      <Pagination page={page} total={q.data?.total ?? 0} limit={PAGE_SIZE} onPage={setPage} />
    </div>
  );
}
