import React, {useEffect, useState} from 'react';
import axios from 'axios';
import {usePage} from '@inertiajs/react';
import MainLayout from '@/layouts/MainLayout';
import AppPageHeader from '@/components/AppPageHeader';
import Modal from '@/components/ui/modal/Modal';
import {Table, TableBody, TableCell, TableContainer, TableHead, TableHeaderCell, TablePagination, TableRow, TableStateRow} from '@/components/ui/table';
import toast from 'react-hot-toast';

type Intake = {id: number; name: string; email?: string; phone?: string; client_type: string; service_requirement: string; description?: string; status: string; client?: {id: number; name: string} | null};
type Pagination = {data: Intake[]; current_page: number; last_page: number; total: number};
const emptyForm = () => ({name: '', email: '', phone: '', client_type: 'individual', service_requirement: '', description: '', status: 'new'});

export default function Intakes(): JSX.Element {
    const {auth} = usePage<{auth: {user: {api_token?: string; user_permissions?: string[]}}}>().props;
    const headers = {headers: {Authorization: `Bearer ${auth.user.api_token}`}};
    const permissions = auth.user.user_permissions ?? [];
    const canCreate = permissions.includes('clients_create');
    const canUpdate = permissions.includes('clients_update');
    const canDelete = permissions.includes('clients_delete');
    const [results, setResults] = useState<Pagination>({data: [], current_page: 1, last_page: 1, total: 0});
    const [page, setPage] = useState(1);
    const [form, setForm] = useState(emptyForm());
    const [editing, setEditing] = useState<Intake | null>(null);
    const [saving, setSaving] = useState(false);
    const [formOpen, setFormOpen] = useState(false);
    const [notesIntake, setNotesIntake] = useState<Intake | null>(null);

    const load = async (nextPage = page) => { const {data} = await axios.get(`/api/client-intakes?page=${nextPage}`, headers); const payload = data.result ?? {}; setResults({data: payload.data ?? [], current_page: payload.current_page ?? nextPage, last_page: payload.last_page ?? 1, total: payload.total ?? 0}); };
    useEffect(() => { load(page).catch(() => toast.error('Unable to load intake register')); }, [page]);
    const openCreate = () => { setEditing(null); setForm(emptyForm()); setFormOpen(true); };
    const openEdit = (intake: Intake) => { setEditing(intake); setForm({name: intake.name, email: intake.email ?? '', phone: intake.phone ?? '', client_type: intake.client_type, service_requirement: intake.service_requirement, description: intake.description ?? '', status: intake.status}); setFormOpen(true); };
    const save = async (event: React.FormEvent) => { event.preventDefault(); setSaving(true); try { if (editing) await axios.put(`/api/client-intakes/${editing.id}`, form, headers); else await axios.post('/api/client-intakes', form, headers); setFormOpen(false); await load(); toast.success(editing ? 'Intake updated' : 'Intake saved'); } catch (error: any) { toast.error(error.response?.data?.message ?? 'Unable to save intake'); } finally { setSaving(false); } };
    const convert = async (intake: Intake) => { try { await axios.post(`/api/client-intakes/${intake.id}/convert`, {}, headers); await load(); toast.success('Intake converted to client'); } catch (error: any) { toast.error(error.response?.data?.message ?? 'Unable to convert intake'); } };
    const remove = async (intake: Intake) => { if (!confirm(`Delete intake for “${intake.name}”?`)) return; try { await axios.delete(`/api/client-intakes/${intake.id}`, headers); await load(); toast.success('Intake deleted'); } catch (error: any) { toast.error(error.response?.data?.message ?? 'Unable to delete intake'); } };

    return <MainLayout><AppPageHeader title="Client Intake" subtitle="Prospective clients" />
        <section className="border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900"><div className="flex items-center justify-between border-b p-5"><h2 className="font-semibold">Intake register</h2>{canCreate && <button className="ti-btn ti-btn-primary" onClick={openCreate}><i className="fa fa-plus mr-2" />New intake</button>}</div>
        <TableContainer><Table><TableHead><TableRow><TableHeaderCell>Prospect</TableHeaderCell><TableHeaderCell>Service</TableHeaderCell><TableHeaderCell>Notes</TableHeaderCell><TableHeaderCell>Status</TableHeaderCell><TableHeaderCell className="text-right">Actions</TableHeaderCell></TableRow></TableHead><TableBody>{results.data.length === 0 ? <TableStateRow colSpan={5} message="No intake records found." /> : results.data.map(intake => <TableRow key={intake.id}><TableCell><div className="font-medium">{intake.name}</div>{intake.email && <div className="text-gray-500"><i className="fa fa-envelope mr-1" />{intake.email}</div>}{intake.phone && <div className="text-gray-500"><i className="fa fa-phone mr-1" />{intake.phone}</div>}{!intake.email && !intake.phone && <div className="text-gray-500">No contact details</div>}</TableCell><TableCell>{intake.service_requirement}</TableCell><TableCell className="max-w-xs whitespace-normal break-words"><span>{intake.description ? `${intake.description.slice(0, 100)}${intake.description.length > 100 ? '...' : ''}` : 'No notes'}</span>{(intake.description?.length ?? 0) > 100 && <button type="button" className="ml-2 text-sm font-medium text-indigo-600 hover:underline" onClick={() => setNotesIntake(intake)}>Read more</button>}</TableCell><TableCell className="capitalize">{intake.status.replace('_', ' ')}</TableCell><TableCell className="text-right">{intake.client ? <span className="text-emerald-600">Client linked</span> : <div className="flex justify-end gap-2">{canCreate && <button title="Convert to client" className="ti-btn ti-btn-soft-success" onClick={() => convert(intake)}><i className="fa fa-user-plus" /></button>}{canUpdate && <button title="Edit intake" className="ti-btn ti-btn-soft-primary" onClick={() => openEdit(intake)}><i className="fa fa-pencil" /></button>}{canDelete && <button title="Delete intake" className="ti-btn ti-btn-soft-danger" onClick={() => remove(intake)}><i className="fa fa-trash" /></button>}</div>}</TableCell></TableRow>)}</TableBody></Table></TableContainer>
        <div className="px-5 pb-5"><TablePagination meta={results} itemCount={results.data.length} currentPage={page} onPageChange={setPage} itemLabel="intakes" /></div></section>
        <Modal open={formOpen} onClose={() => setFormOpen(false)} title={editing ? 'Edit client intake' : 'New client intake'} footer={<><button type="button" className="ti-btn ti-btn-light" onClick={() => setFormOpen(false)}>Cancel</button><button type="submit" form="intake-form" className="ti-btn ti-btn-primary" disabled={saving}>{saving ? 'Saving...' : editing ? 'Update intake' : 'Save intake'}</button></>}>
            <form id="intake-form" onSubmit={save} className="grid gap-4 sm:grid-cols-2">
                <div className="sm:col-span-2"><label htmlFor="intake-name" className="mb-1 block text-sm font-medium text-gray-700">Prospect name</label><input id="intake-name" required value={form.name} onChange={e => setForm({...form,name:e.target.value})} className="ti-form-input" placeholder="Full name or organisation"/></div>
                <div><label htmlFor="intake-email" className="mb-1 block text-sm font-medium text-gray-700">Email address</label><input id="intake-email" type="email" value={form.email} onChange={e => setForm({...form,email:e.target.value})} className="ti-form-input"/></div>
                <div><label htmlFor="intake-phone" className="mb-1 block text-sm font-medium text-gray-700">Phone number</label><input id="intake-phone" value={form.phone} onChange={e => setForm({...form,phone:e.target.value})} className="ti-form-input"/></div>
                <div><label htmlFor="intake-client-type" className="mb-1 block text-sm font-medium text-gray-700">Client type</label><select id="intake-client-type" value={form.client_type} onChange={e => setForm({...form,client_type:e.target.value})} className="ti-form-select"><option value="individual">Individual</option><option value="corporate">Corporate</option><option value="government">Government</option></select></div>
                <div><label htmlFor="intake-status" className="mb-1 block text-sm font-medium text-gray-700">Intake status</label><select id="intake-status" value={form.status} onChange={e => setForm({...form,status:e.target.value})} className="ti-form-select"><option value="new">New</option><option value="contacted">Contacted</option><option value="consultation_scheduled">Consultation scheduled</option><option value="qualified">Qualified</option><option value="declined">Declined</option></select></div>
                <div className="sm:col-span-2"><label htmlFor="intake-service" className="mb-1 block text-sm font-medium text-gray-700">Initial legal service requirement</label><input id="intake-service" required value={form.service_requirement} onChange={e => setForm({...form,service_requirement:e.target.value})} className="ti-form-input"/></div>
                <div className="sm:col-span-2"><label htmlFor="intake-notes" className="mb-1 block text-sm font-medium text-gray-700">Intake notes</label><textarea id="intake-notes" value={form.description} onChange={e => setForm({...form,description:e.target.value})} className="ti-form-textarea"/></div>
            </form>
        </Modal>
        <Modal open={notesIntake !== null} onClose={() => setNotesIntake(null)} title={notesIntake ? `Intake notes: ${notesIntake.name}` : 'Intake notes'} maxWidthClassName="max-w-xl"><div className="whitespace-pre-wrap break-words text-sm leading-6 text-gray-700 dark:text-gray-200">{notesIntake?.description}</div></Modal>
    </MainLayout>;
}
