'use client';

import { useEffect, useState } from 'react';
import { chairmanApi, organizationApi } from '@/lib/api/admin';
import type { Chairman, OrganizationStructure } from '@/types';
import {
    PageHeader, AddButton, Table, TableRow, TableCell, StatusBadge, ActionButton,
    ConfirmDialog, Modal, FormField, Input, Select, Textarea, Toggle,
    SubmitButton, ErrorAlert, EmptyState, LoadingSpinner
} from '@/components/Ui';

export default function ChairmanPage() {
    const [items, setItems] = useState<Chairman[]>([]);
    const [structures, setStructures] = useState<OrganizationStructure[]>([]);
    const [loading, setLoading] = useState(true);
    const [modalOpen, setModalOpen] = useState(false);
    const [editing, setEditing] = useState<Chairman | null>(null);
    const [deleteTarget, setDeleteTarget] = useState<Chairman | null>(null);
    const [deleting, setDeleting] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [form, setForm] = useState({
        organization_structure_id: '',
        period: '',
        welcome_message: '',
        is_current: false,
    });

    const fetchData = async () => {
        try {
            const [cRes, oRes] = await Promise.all([
                chairmanApi.getAll(),
                organizationApi.getAll(),
            ]);
            setItems(cRes.data);
            setStructures(oRes.data);
        } finally { setLoading(false); }
    };
    useEffect(() => { fetchData(); }, []);

    const openCreate = () => {
        setEditing(null);
        setForm({ organization_structure_id: '', period: '', welcome_message: '', is_current: false });
        setError('');
        setModalOpen(true);
    };

    const openEdit = (c: Chairman) => {
        setEditing(c);
        setForm({
            organization_structure_id: String(c.organization_structure_id),
            period: c.period,
            welcome_message: c.welcome_message || '',
            is_current: c.is_current,
        });
        setError('');
        setModalOpen(true);
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault(); setSaving(true); setError('');
        try {
            const data = {
                organization_structure_id: +form.organization_structure_id,
                period: form.period,
                welcome_message: form.welcome_message,
                is_current: form.is_current,
            };
            if (editing) { await chairmanApi.update(editing.id, data); } else { await chairmanApi.create(data); }
            setModalOpen(false); fetchData();
        } catch (err: any) { setError(err.message || 'Failed to save'); } finally { setSaving(false); }
    };

    const handleDelete = async () => {
        if (!deleteTarget) return; setDeleting(true);
        try { await chairmanApi.delete(deleteTarget.id); setDeleteTarget(null); fetchData(); } finally { setDeleting(false); }
    };

    const handleSetCurrent = async (id: number) => {
        try { await chairmanApi.setCurrent(id); fetchData(); } catch (err: any) { alert(err.message); }
    };

    const structureLabel = (s: OrganizationStructure) =>
        `${s.name} — ${s.position}${s.period ? ` (${s.period.name})` : ''}`;

    if (loading) return <LoadingSpinner />;

    return (
        <div className="space-y-6">
            <PageHeader title="Chairman" subtitle="Manage organization chairmen" action={<AddButton onClick={openCreate} />} />

            {items.length === 0 ? (
                <div className="bg-white rounded-xl shadow-sm"><EmptyState /></div>
            ) : (
                <Table headers={['#', 'Name', 'Position', 'Period', 'Welcome Message', 'Current', 'Actions']}>
                    {items.map((c, i) => (
                        <TableRow key={c.id}>
                            <TableCell>{i + 1}</TableCell>
                            <TableCell>
                                <div>
                                    <p className="font-medium">{c.organizationStructure?.name || '-'}</p>
                                    <p className="text-xs text-sec">{c.organizationStructure?.tbm?.tbm || ''}</p>
                                </div>
                            </TableCell>
                            <TableCell>{c.organizationStructure?.position || '-'}</TableCell>
                            <TableCell>{c.period}</TableCell>
                            <TableCell className="max-w-xs">
                                <p className="truncate text-sec text-xs">{c.welcome_message || '-'}</p>
                            </TableCell>
                            <TableCell>
                                <StatusBadge active={c.is_current} activeLabel="Current" inactiveLabel="Former" />
                            </TableCell>
                            <TableCell>
                                <div className="flex gap-1">
                                    {!c.is_current && (
                                        <ActionButton variant="set-current" label="Set as Current" onClick={() => handleSetCurrent(c.id)} />
                                    )}
                                    <ActionButton variant="edit" onClick={() => openEdit(c)} />
                                    <ActionButton variant="delete" onClick={() => setDeleteTarget(c)} />
                                </div>
                            </TableCell>
                        </TableRow>
                    ))}
                </Table>
            )}

            <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Edit Chairman' : 'Add Chairman'} size="lg">
                <form onSubmit={handleSubmit} className="space-y-4">
                    <ErrorAlert message={error} />
                    <FormField label="Organization Structure Member" required>
                        <Select
                            value={form.organization_structure_id}
                            onChange={e => setForm(p => ({ ...p, organization_structure_id: e.target.value }))}
                            required
                        >
                            <option value="">Select Member from Structure</option>
                            {structures.map(s => (
                                <option key={s.id} value={s.id}>{structureLabel(s)}</option>
                            ))}
                        </Select>
                    </FormField>
                    <FormField label="Period" required>
                        <Input
                            value={form.period}
                            onChange={e => setForm(p => ({ ...p, period: e.target.value }))}
                            placeholder="e.g. 2022-2024"
                            required
                        />
                    </FormField>
                    <FormField label="Welcome Message">
                        <Textarea
                            value={form.welcome_message}
                            onChange={e => setForm(p => ({ ...p, welcome_message: e.target.value }))}
                            rows={4}
                            placeholder="Chairman's welcome message..."
                        />
                    </FormField>
                    <Toggle checked={form.is_current} onChange={v => setForm(p => ({ ...p, is_current: v }))} label="Set as Current Chairman" />
                    <SubmitButton loading={saving} />
                </form>
            </Modal>

            <ConfirmDialog
                isOpen={!!deleteTarget}
                onClose={() => setDeleteTarget(null)}
                onConfirm={handleDelete}
                loading={deleting}
                title="Delete Chairman"
                message={`Delete chairman "${deleteTarget?.organizationStructure?.name}"?`}
            />
        </div>
    );
}