import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { Plus, Edit2, Trash2, X, Pin, Bell } from 'lucide-react';

interface Announcement {
    id: number;
    title: string;
    content: string;
    type: string;
    priority: string;
    is_pinned: boolean;
    publish_date: string | null;
    expiry_date: string | null;
    target_audience: string;
    company_id: number | null;
    company: { id: number; name: string } | null;
    creator: { id: number; name: string } | null;
    created_at: string;
}

interface Props {
    announcements: Announcement[];
    companies: { id: number; name: string }[];
}

const PRIORITY_COLORS: Record<string, string> = {
    low: 'bg-gray-100 text-gray-600',
    normal: 'bg-blue-50 text-blue-700',
    high: 'bg-amber-50 text-amber-700',
    urgent: 'bg-red-50 text-red-700',
};

const TYPE_COLORS: Record<string, string> = {
    general: 'bg-slate-100 text-slate-600',
    hr: 'bg-purple-50 text-purple-700',
    operations: 'bg-cyan-50 text-cyan-700',
    event: 'bg-green-50 text-green-700',
};

const blank = { title: '', content: '', type: 'general', priority: 'normal', is_pinned: false, publish_date: '', expiry_date: '', target_audience: 'all', company_id: '' };

export default function AnnouncementsIndex({ announcements, companies }: Props) {
    const { auth, flash } = usePage<any>().props;
    const isSuperAdmin = auth?.user?.role === 'super_admin';
    const [showModal, setShowModal] = useState(false);
    const [editing, setEditing] = useState<Announcement | null>(null);
    const [form, setForm] = useState<any>(blank);

    function openCreate() { setEditing(null); setForm(blank); setShowModal(true); }
    function openEdit(a: Announcement) {
        setEditing(a);
        setForm({ title: a.title, content: a.content, type: a.type, priority: a.priority, is_pinned: a.is_pinned, publish_date: a.publish_date ?? '', expiry_date: a.expiry_date ?? '', target_audience: a.target_audience, company_id: a.company_id ?? '' });
        setShowModal(true);
    }

    function save() {
        const payload = { ...form, company_id: form.company_id || null };
        if (editing) {
            router.patch(`/hr-portal/announcements/${editing.id}`, payload, { onSuccess: () => setShowModal(false) });
        } else {
            router.post('/hr-portal/announcements', payload, { onSuccess: () => setShowModal(false) });
        }
    }

    function del(a: Announcement) {
        if (!confirm(`Delete "${a.title}"?`)) return;
        router.delete(`/hr-portal/announcements/${a.id}`);
    }

    const f = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setForm((p: any) => ({ ...p, [k]: e.target.value }));

    return (
        <AppLayout title="Announcements">
            <Head title="Announcements" />
            {flash?.success && <div className="mb-4 rounded-lg bg-green-50 px-4 py-2.5 text-sm text-green-700">{flash.success}</div>}

            <div className="mb-5 flex items-center justify-between">
                <p className="text-sm text-gray-500">{announcements.length} announcement{announcements.length !== 1 ? 's' : ''}</p>
                <button onClick={openCreate} className="flex items-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">
                    <Plus className="h-4 w-4" /> New Announcement
                </button>
            </div>

            {announcements.length === 0 ? (
                <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-gray-200 py-16">
                    <Bell className="mb-3 h-10 w-10 text-gray-300" />
                    <p className="text-gray-500">No announcements yet.</p>
                    <button onClick={openCreate} className="mt-3 text-sm text-blue-600 hover:underline">Create the first one</button>
                </div>
            ) : (
                <div className="space-y-3">
                    {announcements.map(a => (
                        <div key={a.id} className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
                            <div className="flex items-start justify-between gap-4">
                                <div className="flex-1 min-w-0">
                                    <div className="mb-1.5 flex flex-wrap items-center gap-2">
                                        {a.is_pinned && <Pin className="h-3.5 w-3.5 text-amber-500" />}
                                        <span className="text-base font-semibold text-gray-900">{a.title}</span>
                                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${PRIORITY_COLORS[a.priority] ?? 'bg-gray-100 text-gray-600'}`}>{a.priority}</span>
                                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${TYPE_COLORS[a.type] ?? 'bg-gray-100 text-gray-600'}`}>{a.type}</span>
                                        {a.company && <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">{a.company.name}</span>}
                                        {!a.company && <span className="rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-600">All companies</span>}
                                    </div>
                                    <p className="text-sm text-gray-600 line-clamp-2">{a.content}</p>
                                    <div className="mt-2 flex flex-wrap gap-4 text-xs text-gray-400">
                                        {a.publish_date && <span>Publish: {a.publish_date}</span>}
                                        {a.expiry_date && <span>Expires: {a.expiry_date}</span>}
                                        <span>Audience: {a.target_audience}</span>
                                        {a.creator && <span>By: {a.creator.name}</span>}
                                    </div>
                                </div>
                                <div className="flex flex-shrink-0 gap-1">
                                    <button onClick={() => openEdit(a)} className="rounded-md p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-700"><Edit2 className="h-4 w-4" /></button>
                                    <button onClick={() => del(a)} className="rounded-md p-1.5 text-gray-400 hover:bg-red-50 hover:text-red-600"><Trash2 className="h-4 w-4" /></button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {showModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
                    <div className="w-full max-w-lg rounded-2xl bg-white shadow-xl">
                        <div className="flex items-center justify-between border-b border-gray-100 px-6 py-4">
                            <h2 className="text-base font-semibold text-gray-900">{editing ? 'Edit Announcement' : 'New Announcement'}</h2>
                            <button onClick={() => setShowModal(false)}><X className="h-5 w-5 text-gray-400" /></button>
                        </div>
                        <div className="space-y-4 px-6 py-4">
                            <div>
                                <label className="mb-1 block text-xs font-medium text-gray-600">Title *</label>
                                <input value={form.title} onChange={f('title')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm" />
                            </div>
                            <div>
                                <label className="mb-1 block text-xs font-medium text-gray-600">Content *</label>
                                <textarea value={form.content} onChange={f('content')} rows={4} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm" />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="mb-1 block text-xs font-medium text-gray-600">Type</label>
                                    <select value={form.type} onChange={f('type')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm">
                                        {['general', 'hr', 'operations', 'event'].map(t => <option key={t} value={t}>{t}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label className="mb-1 block text-xs font-medium text-gray-600">Priority</label>
                                    <select value={form.priority} onChange={f('priority')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm">
                                        {['low', 'normal', 'high', 'urgent'].map(p => <option key={p} value={p}>{p}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label className="mb-1 block text-xs font-medium text-gray-600">Publish Date</label>
                                    <input type="date" value={form.publish_date} onChange={f('publish_date')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm" />
                                </div>
                                <div>
                                    <label className="mb-1 block text-xs font-medium text-gray-600">Expiry Date</label>
                                    <input type="date" value={form.expiry_date} onChange={f('expiry_date')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm" />
                                </div>
                            </div>
                            {isSuperAdmin && (
                                <div>
                                    <label className="mb-1 block text-xs font-medium text-gray-600">Company (leave empty for all)</label>
                                    <select value={form.company_id} onChange={f('company_id')} className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm">
                                        <option value="">All Companies</option>
                                        {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                    </select>
                                </div>
                            )}
                            <label className="flex cursor-pointer items-center gap-2 text-sm text-gray-700">
                                <input type="checkbox" checked={form.is_pinned} onChange={e => setForm((p: any) => ({...p, is_pinned: e.target.checked}))} className="rounded" />
                                Pin this announcement
                            </label>
                        </div>
                        <div className="flex justify-end gap-2 border-t border-gray-100 px-6 py-4">
                            <button onClick={() => setShowModal(false)} className="rounded-md border border-gray-200 px-4 py-2 text-sm text-gray-600 hover:bg-gray-50">Cancel</button>
                            <button onClick={save} className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">{editing ? 'Save Changes' : 'Publish'}</button>
                        </div>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}
