import React, {useEffect, useState} from 'react';
import {usePage} from '@inertiajs/react';
import {makeGetRequest} from '@/lib/request';
import Modal from '@/components/ui/modal/Modal';

type Props = {
    clientId?: number;
    matterId?: number;
    matters?: Array<{id: number; reference_number: string}>;
    onTotal?: (total: number) => void;
};

const types = ['email', 'phone', 'meeting', 'video', 'other', 'sms', 'portal'];
const label = (value?: string | null) => String(value || '-').replaceAll('_', ' ').replace(/\b\w/g, char => char.toUpperCase());
const formatDate = (value?: string | null) => value ? new Date(value).toLocaleString() : '-';

export default function CommunicationTimeline({clientId, matterId, matters = [], onTotal}: Props): JSX.Element {
    const {auth} = usePage<{auth: {user: any}}>().props;
    const token = auth?.user?.api_token ?? auth?.user?.token;
    const [result, setResult] = useState<any>({data: [], current_page: 1, last_page: 1, total: 0});
    const [page, setPage] = useState(1);
    const [filters, setFilters] = useState({type: '', matter_id: matterId ? String(matterId) : '', date_from: '', date_to: ''});
    const [active, setActive] = useState<any | null>(null);
    const [loading, setLoading] = useState(false);

    const load = async (nextPage = page) => {
        setLoading(true);
        try {
            const params = new URLSearchParams({page: String(nextPage), per_page: '8'});
            if (clientId) params.set('client_id', String(clientId));
            if (matterId) params.set('matter_id', String(matterId));
            Object.entries(filters).forEach(([key, value]) => {
                if (value && !(key === 'matter_id' && matterId)) params.set(key, value);
            });
            const response = await makeGetRequest('/api/communications?' + params.toString(), {token});
            const payload = response.data?.result ?? response.data ?? {};
            setResult({...payload, data: Array.isArray(payload.data) ? payload.data : []});
            onTotal?.(payload.total ?? 0);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        setPage(1);
        load(1);
    }, [clientId, matterId, filters.type, filters.matter_id, filters.date_from, filters.date_to]);

    useEffect(() => {
        if (page > 1) load(page);
    }, [page]);

    return (
        <div>
            <div className="mb-4 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
                <select aria-label="Communication type" className="ti-form-input" value={filters.type}
                        onChange={event => setFilters({...filters, type: event.target.value})}>
                    <option value="">All types</option>
                    {types.map(type => <option key={type} value={type}>{label(type)}</option>)}
                </select>
                {!matterId && matters.length > 0 && (
                    <select aria-label="Matter" className="ti-form-input" value={filters.matter_id}
                            onChange={event => setFilters({...filters, matter_id: event.target.value})}>
                        <option value="">All matters</option>
                        {matters.map(matter => <option key={matter.id} value={matter.id}>{matter.reference_number}</option>)}
                    </select>
                )}
                <input aria-label="From date" type="date" className="ti-form-input" value={filters.date_from}
                       onChange={event => setFilters({...filters, date_from: event.target.value})}/>
                <input aria-label="To date" type="date" className="ti-form-input" value={filters.date_to}
                       onChange={event => setFilters({...filters, date_to: event.target.value})}/>
            </div>

            {loading ? <p className="py-6 text-center text-sm text-gray-500">Loading communications...</p>
                : result.data.length === 0 ? <p className="py-6 text-center text-sm text-gray-500">No communications found.</p>
                    : <div className="divide-y border-y">
                        {result.data.map((communication: any) => (
                            <button key={communication.id} type="button" onClick={() => setActive(communication)}
                                    className="flex w-full items-start gap-3 py-3 text-left hover:bg-gray-50">
                                <span className="inline-flex h-8 w-8 shrink-0 items-center justify-center text-indigo-600">
                                    <i className={'fa ' + (communication.type === 'phone' ? 'fa-phone' : communication.type === 'meeting' ? 'fa-users' : communication.type === 'video' ? 'fa-video-camera' : 'fa-envelope')}/>
                                </span>
                                <span className="min-w-0 flex-1">
                                    <span className="block truncate text-sm font-semibold">{communication.subject || label(communication.type)}</span>
                                    <span className="mt-1 block text-xs text-gray-500">
                                        {label(communication.type)}{communication.direction ? ' | ' + label(communication.direction) : ''}
                                        {' | '}{communication.staff?.name ?? 'Unknown staff'}
                                        {communication.matter ? ' | ' + communication.matter.reference_number : ''}
                                        {communication.consultation ? ' | Consultation' : ''}
                                    </span>
                                    <span className="mt-1 block text-xs text-gray-500">{formatDate(communication.communication_date)}</span>
                                </span>
                                {communication.follow_up_required && (
                                    <span className={'text-xs font-medium ' + (communication.follow_up_completed_at ? 'text-emerald-600' : 'text-amber-600')}>
                                        {communication.follow_up_completed_at ? 'Follow-up complete' : 'Follow-up due'}
                                    </span>
                                )}
                            </button>
                        ))}
                    </div>}

            <div className="mt-4 flex items-center justify-between">
                <span className="text-xs text-gray-500">{result.total ?? 0} communication(s)</span>
                <div className="flex gap-2">
                    <button type="button" className="ti-btn ti-btn-light py-1 px-2 text-xs" disabled={page <= 1} onClick={() => setPage(page - 1)}>Prev</button>
                    <span className="px-2 py-1 text-xs">{result.current_page ?? page} / {result.last_page ?? 1}</span>
                    <button type="button" className="ti-btn ti-btn-light py-1 px-2 text-xs" disabled={page >= (result.last_page ?? 1)} onClick={() => setPage(page + 1)}>Next</button>
                </div>
            </div>

            <Modal open={Boolean(active)} onClose={() => setActive(null)} title="Communication details" maxWidthClassName="max-w-xl"
                   footer={<button type="button" className="ti-btn ti-border" onClick={() => setActive(null)}>Close</button>}>
                {active && <div className="space-y-4 text-sm">
                    <dl className="grid grid-cols-2 gap-3">
                        <div><dt className="text-gray-500">Type</dt><dd>{label(active.type)}</dd></div>
                        <div><dt className="text-gray-500">Direction</dt><dd>{label(active.direction)}</dd></div>
                        <div><dt className="text-gray-500">Date</dt><dd>{formatDate(active.communication_date)}</dd></div>
                        <div><dt className="text-gray-500">Responsible staff</dt><dd>{active.staff?.name ?? '-'}</dd></div>
                        <div><dt className="text-gray-500">Matter</dt><dd>{active.matter?.reference_number ?? '-'}</dd></div>
                        <div><dt className="text-gray-500">Consultation</dt><dd>{active.consultation ? formatDate(active.consultation.scheduled_at) : '-'}</dd></div>
                    </dl>
                    <div><h4 className="font-semibold">{active.subject || 'No subject'}</h4><p className="mt-1 whitespace-pre-wrap text-gray-700">{active.content || 'No notes recorded.'}</p></div>
                    {active.follow_up_required && <div className="border-t pt-3"><h4 className="font-semibold">Follow-up</h4><p>{active.follow_up_description}</p><p className="text-gray-500">{active.follow_up_user?.name ?? '-'} | {formatDate(active.follow_up_at)}</p></div>}
                    {active.documents?.length > 0 && <div className="border-t pt-3"><h4 className="font-semibold">Documents</h4>{active.documents.map((document: any) => <p key={document.id}>{document.title}</p>)}</div>}
                </div>}
            </Modal>
        </div>
    );
}
