'use client';

import { useEffect, useState } from 'react';
import { Plus, Pin, Users, AlertTriangle } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { useLiveRefresh } from '@/lib/realtime';
import AttachmentPicker, { Attachment } from '@/components/AttachmentPicker';
import AiPolishButton from '@/components/AiPolishButton';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Member = { id: number; name: string; role: string };
type Post = {
  id: number; title: string; body: string; category: string; audience: string; pinned: boolean; unread: boolean;
  recipientCount: number; createdAt: string; author: { id: number; name: string };
};
const CATEGORY_STYLE: Record<string, string> = { URGENT: 'bg-red-100 text-red-700', POLICY: 'bg-blue-100 text-blue-700', EVENT: 'bg-purple-100 text-purple-700', CELEBRATION: 'bg-pink-100 text-pink-700', INFO: 'bg-gray-100 text-gray-700' };
const emptyForm = { title: '', body: '', category: 'INFO', audience: 'SELECTED', recipientIds: [] as number[], pinned: false };

export default function InformationPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [posts, setPosts] = useState<Post[]>([]);
  const [members, setMembers] = useState<Member[]>([]);
  const [canBroadcast, setCanBroadcast] = useState(false);
  const [filter, setFilter] = useState<'all' | 'unread' | 'pinned' | 'mine'>('all');
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [files, setFiles] = useState<Attachment[]>([]);
  const [openId, setOpenId] = useState<number | null>(null);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [p, m] = await Promise.all([
        adminApiFetch(`/admin/information?filter=${filter}`, accessToken, appSecretProof),
        adminApiFetch('/admin/tasks/members', accessToken, appSecretProof),
      ]);
      setPosts(p.posts || []); setCanBroadcast(p.canBroadcast); setMembers(m.members || []);
    } finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof, filter]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['information'], load);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch('/admin/information', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ ...form, attachments: files }) });
      show('success', 'Posted.');
      setForm(emptyForm); setFiles([]); setCreating(false); load();
    } catch (e2) { show('error', (e2 as Error).message === 'BROADCAST_NOT_ALLOWED' ? 'You can only post to selected members, not everyone.' : 'Could not post that.'); }
  }

  async function open(id: number) {
    if (!accessToken || !appSecretProof) return;
    setOpenId(id);
    load(); // refresh unread state after the read happens server-side
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">Information</h1>
        <button onClick={() => setCreating(true)} className="flex items-center gap-1.5 bg-brand-red text-white text-xs font-semibold px-3 py-2 rounded-lg"><Plus size={14} /> New post</button>
      </div>

      <div className="flex gap-1">
        {(['all', 'unread', 'pinned', 'mine'] as const).map((f) => (
          <button key={f} onClick={() => setFilter(f)} className={`text-xs font-semibold px-3 py-1.5 rounded-lg capitalize ${filter === f ? 'bg-brand-charcoal text-white' : 'bg-white border border-brand-border text-gray-600'}`}>{f}</button>
        ))}
      </div>

      {loading ? <TableSkeleton rows={5} cols={4} /> : (
        <div className="grid gap-2">
          {posts.map((p) => (
            <button key={p.id} onClick={() => open(p.id)} className={`text-left bg-white border rounded-xl p-4 hover:shadow-md transition-shadow ${p.unread ? 'border-brand-red' : 'border-brand-border'}`}>
              <div className="flex justify-between items-start gap-3">
                <p className="text-sm font-semibold flex items-center gap-1.5">{p.pinned && <Pin size={12} className="text-brand-red" />}{p.category === 'URGENT' && <AlertTriangle size={12} className="text-red-600" />}{p.title}</p>
                <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full shrink-0 ${CATEGORY_STYLE[p.category]}`}>{p.category}</span>
              </div>
              <p className="text-xs text-gray-500 mt-1 line-clamp-2">{p.body}</p>
              <p className="text-[11px] text-gray-400 mt-2 flex items-center gap-2"><Users size={11} /> {p.audience === 'ALL' ? 'Everyone' : `${p.recipientCount} member(s)`} &bull; {p.author.name} &bull; {new Date(p.createdAt).toLocaleDateString()}</p>
            </button>
          ))}
          {posts.length === 0 && <p className="text-sm text-gray-400">Nothing here.</p>}
        </div>
      )}

      {creating && (
        <Modal title="New post" onClose={() => setCreating(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <input required placeholder="Title" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <textarea required placeholder="Message" value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })} rows={6} className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <AiPolishButton text={form.body} kind="announcement" onAccept={(t) => setForm((f) => ({ ...f, body: t }))} />
            <div className="grid grid-cols-2 gap-2">
              <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="border border-brand-border rounded-lg px-2 py-2 text-sm">
                {['INFO', 'POLICY', 'URGENT', 'EVENT', 'CELEBRATION'].map((c) => <option key={c} value={c}>{c}</option>)}
              </select>
              <select value={form.audience} onChange={(e) => setForm({ ...form, audience: e.target.value })} className="border border-brand-border rounded-lg px-2 py-2 text-sm">
                <option value="SELECTED">Selected members</option>
                {canBroadcast && <option value="ALL">Everyone</option>}
              </select>
            </div>
            {form.audience === 'SELECTED' && (
              <select multiple value={form.recipientIds.map(String)} onChange={(e) => setForm({ ...form, recipientIds: Array.from(e.target.selectedOptions, (o) => Number(o.value)) })}
                className="w-full border border-brand-border rounded-lg px-2 py-2 text-sm h-28">
                {members.map((m) => <option key={m.id} value={m.id}>{m.name} ({m.role})</option>)}
              </select>
            )}
            {canBroadcast && (
              <label className="flex items-center gap-2 text-xs"><input type="checkbox" checked={form.pinned} onChange={(e) => setForm({ ...form, pinned: e.target.checked })} className="accent-brand-red" /> Pin to the top</label>
            )}
            <AttachmentPicker attachments={files} onChange={setFiles} />
            <button className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg">Post</button>
          </form>
        </Modal>
      )}

      {openId && <PostDetail id={openId} onClose={() => setOpenId(null)} onChanged={load} canBroadcast={canBroadcast} />}
    </div>
  );
}

function PostDetail({ id, onClose, onChanged, canBroadcast }: { id: number; onClose: () => void; onChanged: () => void; canBroadcast: boolean }) {
  const { accessToken, appSecretProof } = useAuth();
  const [data, setData] = useState<{ post: Post; readers: { id: number; name: string; readAt: string | null }[] | null } | null>(null);

  useEffect(() => {
    if (!accessToken || !appSecretProof) return;
    adminApiFetch(`/admin/information/${id}`, accessToken, appSecretProof).then(setData).catch(() => null);
  }, [id, accessToken, appSecretProof]);

  if (!data) return null;
  return (
    <Modal title={data.post.title} onClose={onClose} wide>
      <p className="text-sm text-gray-700 whitespace-pre-wrap">{data.post.body}</p>
      <p className="text-xs text-gray-400 mt-3">{data.post.author.name} &bull; {new Date(data.post.createdAt).toLocaleString()}</p>
      {data.readers && (
        <div className="mt-4 border-t border-brand-border pt-3">
          <p className="text-xs font-semibold mb-1">Read by {data.readers.filter((r) => r.readAt).length}/{data.readers.length}</p>
          <div className="flex flex-wrap gap-1.5">
            {data.readers.map((r) => <span key={r.id} className={`text-[10px] px-2 py-0.5 rounded-full ${r.readAt ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'}`}>{r.name}</span>)}
          </div>
        </div>
      )}
    </Modal>
  );
}
