'use client';

import { useEffect, useState } from 'react';
import { contactApi } from '@/lib/api/admin';
import type { Contact } from '@/types';
import {
    PageHeader, AddButton, Table, TableRow, TableCell, StatusBadge, ActionButton,
    ConfirmDialog, Modal, FormField, Input, Textarea, Toggle, SubmitButton,
    ErrorAlert, EmptyState, LoadingSpinner
} from '@/components/Ui';
import { EnvelopeIcon, PhoneIcon, MapPinIcon } from '@heroicons/react/24/outline';

export default function ContactPage() {
    const [items, setItems] = useState<Contact[]>([]);
    const [loading, setLoading] = useState(true);
    const [modalOpen, setModalOpen] = useState(false);
    const [editing, setEditing] = useState<Contact | null>(null);
    const [deleteTarget, setDeleteTarget] = useState<Contact | null>(null);
    const [deleting, setDeleting] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [form, setForm] = useState({ email: '', phone: '', address: '', is_active: false });

    const fetchData = async () => { try { const r = await contactApi.getAll(); setItems(r.data); } finally { setLoading(false); } };
    useEffect(() => { fetchData(); }, []);

    const openCreate = () => { setEditing(null); setForm({ email: '', phone: '', address: '', is_active: false }); setError(''); setModalOpen(true); };
    const openEdit = (c: Contact) => { setEditing(c); setForm({ email: c.email || '', phone: c.phone || '', address: c.address || '', is_active: c.is_active }); setError(''); setModalOpen(true); };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault(); setSaving(true); setError('');
        try {
            if (editing) { await contactApi.update(editing.id, form); } else { await contactApi.create(form); }
            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 contactApi.delete(deleteTarget.id); setDeleteTarget(null); fetchData(); } finally { setDeleting(false); }
    };

    const handleSetActive = async (id: number) => {
        try { await contactApi.setActive(id); fetchData(); } catch (err: any) { alert(err.message); }
    };

    if (loading) return <LoadingSpinner />;

    return (
        <div className="space-y-6">
            <PageHeader title="Contact" subtitle="Manage contact information" action={<AddButton onClick={openCreate} />} />

            {items.length === 0 ? <div className="bg-white rounded-xl shadow-sm"><EmptyState /></div> : (
                <Table headers={['#', 'Email', 'Phone', 'Address', 'Status', 'Actions']}>
                    {items.map((c, i) => (
                        <TableRow key={c.id}>
                            <TableCell>{i + 1}</TableCell>
                            <TableCell>
                                {c.email ? (
                                    <div className="flex items-center gap-1.5"><EnvelopeIcon className="w-4 h-4 text-sec" /><span>{c.email}</span></div>
                                ) : <span className="text-sec">-</span>}
                            </TableCell>
                            <TableCell>
                                {c.phone ? (
                                    <div className="flex items-center gap-1.5"><PhoneIcon className="w-4 h-4 text-sec" /><span>{c.phone}</span></div>
                                ) : <span className="text-sec">-</span>}
                            </TableCell>
                            <TableCell className="max-w-xs">
                                {c.address ? (
                                    <div className="flex items-start gap-1.5"><MapPinIcon className="w-4 h-4 text-sec flex-shrink-0 mt-0.5" /><p className="truncate">{c.address}</p></div>
                                ) : <span className="text-sec">-</span>}
                            </TableCell>
                            <TableCell><StatusBadge active={c.is_active} activeLabel="Active" inactiveLabel="Inactive" /></TableCell>
                            <TableCell>
                                <div className="flex gap-1">
                                    {!c.is_active && <ActionButton variant="set-active" label="Set Active" onClick={() => handleSetActive(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 Contact' : 'Add Contact'}>
                <form onSubmit={handleSubmit} className="space-y-4">
                    <ErrorAlert message={error} />
                    <FormField label="Email"><Input type="email" value={form.email} onChange={e => setForm(p => ({ ...p, email: e.target.value }))} placeholder="contact@organization.com" /></FormField>
                    <FormField label="Phone"><Input value={form.phone} onChange={e => setForm(p => ({ ...p, phone: e.target.value }))} placeholder="+62 xxx xxxx xxxx" /></FormField>
                    <FormField label="Address"><Textarea value={form.address} onChange={e => setForm(p => ({ ...p, address: e.target.value }))} rows={3} placeholder="Full address..." /></FormField>
                    <Toggle checked={form.is_active} onChange={v => setForm(p => ({ ...p, is_active: v }))} label="Set as Active Contact" />
                    <SubmitButton loading={saving} />
                </form>
            </Modal>

            <ConfirmDialog isOpen={!!deleteTarget} onClose={() => setDeleteTarget(null)} onConfirm={handleDelete} loading={deleting} title="Delete Contact" message="Delete this contact entry?" />
        </div>
    );
}