import React, {useEffect, useRef, useState} from 'react';
import {makeDeleteRequest, makeGetRequest, makePostRequest} from '@/lib/request';
import {usePage} from '@inertiajs/react';
import {notify} from '@/lib/notify';

export default function Index() {
    const {auth} = usePage<{ auth: { user: any } }>().props;
    const token = auth?.user?.api_token ?? auth?.user?.token ?? undefined;

    const [results, setResults] = useState<any>({data: [], current_page: 1, last_page: 1, total: 0});
    const [page, setPage] = useState<number>(1);
    const [query, setQuery] = useState<string>('');
    const [loading, setLoading] = useState<boolean>(false);
    const [active, setActive] = useState<any | null>(null);
    const [createOpen, setCreateOpen] = useState<boolean>(false);
    const [clients, setClients] = useState<any[]>([]);

    const fetch = async (p = page, q = query) => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            params.append('page', String(p));
            if (q) params.append('search', q);
            const res = await makeGetRequest(`/api/communications?${params.toString()}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? [];
            setResults({...payload, data: Array.isArray(list) ? list : []});
        } catch (e: any) {
            notify.toastErrorMessage('Failed to load communications');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetch(1, query);
    }, [query]);
    useEffect(() => {
        fetch(page, query);
    }, [page]);

    useEffect(() => {
        // load clients for create select
        const load = async () => {
            try {
                const res = await makeGetRequest('/api/clients?per_page=200', {token});
                const payload = res.data?.result ?? res.data ?? {};
                const list = payload?.data ?? [];
                setClients(Array.isArray(list) ? list : []);
            } catch (e) {
                // ignore
            }
        };
        load();
    }, []);

    const gotoPage = (p: number) => {
        if (!results) return;
        const last = results?.last_page ?? 1;
        if (p < 1 || p > last) return;
        setPage(p);
    };

    const view = (c: any) => setActive(c);

    const remove = async (c: any) => {
        if (!confirm('Delete this communication?')) return;
        try {
            await makeDeleteRequest(`/api/communications/${c.id}`, {token});
            notify.toastSuccessMessage('Communication deleted');
            fetch(page, query);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to delete');
        }
    };

    // Create form state
    const [form, setForm] = useState<any>({
        client_profile_id: '',
        type: 'email',
        subject: '',
        content: '',
        communication_date: new Date().toISOString().slice(0, 10)
    });
    const [attachments, setAttachments] = useState<File[]>([]);
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const [dragOver, setDragOver] = useState(false);

    const handleFilePick = (file: File) => {
        // basic validation: max 50MB per file
        if (file.size > 50 * 1024 * 1024) {
            notify.toastErrorMessage('Each file must be smaller than 50 MB');
            return;
        }
        setAttachments(prev => [...prev, file]);
    };

    const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = Array.from(e.target.files || []);
        files.forEach(handleFilePick);
    };

    const onDropFiles = (e: React.DragEvent) => {
        e.preventDefault();
        setDragOver(false);
        const files = Array.from(e.dataTransfer.files || []);
        files.forEach(handleFilePick);
    };

    const removeAttachment = (index: number) => {
        setAttachments(prev => prev.filter((_, i) => i !== index));
    };
    const [saving, setSaving] = useState(false);

    const submitCreate = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);
        try {
            let payload: any = form;
            if (attachments && attachments.length > 0) {
                const fd = new FormData();
                Object.keys(form).forEach(k => {
                    if (form[k] !== undefined && form[k] !== null) fd.append(k, form[k]);
                });
                attachments.forEach((f) => fd.append('attachments[]', f));
                payload = fd;
            }
            await makePostRequest('/api/communications', payload, {token});
            notify.toastSuccessMessage('Communication created');
            setCreateOpen(false);
            fetch(1, '');
        } catch (err: any) {
            notify.toastErrorMessage(err?.response?.data?.message || 'Failed to create');
        } finally {
            setSaving(false);
        }
    };

    return (
        <>
            <div className="bg-white rounded-lg shadow p-6">
                <div className="flex justify-between mb-4">
                    <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search communications"
                           className="ti-form-input max-w-sm"/>
                    <div>
                        <button onClick={() => setCreateOpen(true)} className="ti-btn ti-btn-primary">
                            <i className="ri ri-edit-line mr-2"></i> Add Communication
                        </button>
                    </div>
                </div>

                <div className="overflow-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                        <tr>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Client</th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Subject</th>
                            <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                            <th className="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Actions</th>
                        </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200">
                        {loading ? (
                            <tr>
                                <td colSpan={5} className="p-6 text-center">Loading...</td>
                            </tr>
                        ) : results.data.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="p-6 text-center">No communications found</td>
                            </tr>
                        ) : results.data.map((c: any) => (
                            <tr key={c.id}>
                                <td className="px-4 py-2 text-sm">{c.client?.name ?? '-'}</td>
                                <td className="px-4 py-2 text-sm">{c.type.toUpperCase()}</td>
                                <td className="px-4 py-2 text-sm">{c.subject ?? '-'}</td>
                                <td className="px-4 py-2 text-sm">{new Date(c.communication_date).toLocaleDateString()}</td>
                                <td className="px-4 py-2 text-sm text-right">
                                    <div className="hs-tooltip ti-main-tooltip inline-flex gap-2">
                                        <button
                                            type="button"
                                            onClick={() => remove(c)}
                                            className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-danger"
                                            title="Delete"
                                        >
                                            <i className="ti ti-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                </div>

                <div className="flex items-center justify-between mt-4">
                    <div
                        className="text-sm text-gray-600">showing {results.data?.length} of {results.total} items
                    </div>
                    <div className="flex items-center gap-2">
                        <button disabled={results.current_page <= 1}
                                onClick={() => gotoPage((results.current_page ?? 1) - 1)}
                                className="px-2 py-1 border rounded">Prev
                        </button>
                        {Array.from({length: results.last_page ?? 1}).map((_, i) => (
                            <button key={i} onClick={() => gotoPage(i + 1)}
                                    className={`px-2 py-1 border rounded ${(results.current_page ?? 1) === i + 1 ? 'bg-indigo-600 text-white' : ''}`}>{i + 1}</button>
                        ))}
                        <button disabled={(results.current_page ?? 1) >= (results.last_page ?? 1)}
                                onClick={() => gotoPage((results.current_page ?? 1) + 1)}
                                className="px-2 py-1 border rounded">Next
                        </button>
                    </div>
                </div>
            </div>

            {/* Create modal */}
            {createOpen && (
                <div role="dialog" aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-xl max-h-[80vh] overflow-auto">
                        <form onSubmit={submitCreate} className="space-y-3">
                            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                                <h3 className="text-base font-semibold text-gray-800">New Communication</h3>
                                <button
                                    type="button"
                                    className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
                                    onClick={() => setCreateOpen(false)}
                                    aria-label="Close"
                                >
                                    <i className="ri ri-close-line text-lg"></i>
                                </button>
                            </div>

                            <div className="px-5 py-5 space-y-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Client</label>
                                    <select className="ti-form-select" value={form.client_profile_id}
                                            onChange={e => setForm({
                                                ...form,
                                                client_profile_id: Number(e.target.value)
                                            })}>
                                        <option value="">Select client</option>
                                        {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Type</label>
                                    <select className="ti-form-select" value={form.type}
                                            onChange={e => setForm({...form, type: e.target.value})}>
                                        <option value="email">Email</option>
                                        <option value="phone">Phone</option>
                                        <option value="meeting">Meeting</option>
                                        <option value="video">Video</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Subject</label>
                                    <input className="ti-form-input" value={form.subject}
                                           onChange={e => setForm({...form, subject: e.target.value})}/>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Content</label>
                                    <textarea className="ti-form-input" rows={6} value={form.content}
                                              onChange={e => setForm({...form, content: e.target.value})}/>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Attachments</label>

                                    <div
                                        onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                                        onDragLeave={() => setDragOver(false)}
                                        onDrop={onDropFiles}
                                        onClick={() => fileInputRef.current?.click()}
                                        className={`h-36 flex flex-col items-center justify-center gap-2 border-2 border-dashed rounded-lg cursor-pointer transition-colors select-none ${
                                            dragOver
                                                ? 'border-indigo-500 bg-indigo-50'
                                                : 'border-gray-300 hover:border-indigo-400 hover:bg-gray-50'
                                        }`}
                                    >
                                        <i className={`fas fa-cloud-upload-alt text-2xl ${dragOver ? 'text-indigo-500' : 'text-gray-400'}`}></i>
                                        <p className="text-sm text-gray-500">
                                            <span className="font-medium text-indigo-600">Click to upload</span>
                                            &nbsp;or drag &amp; drop files here
                                        </p>
                                        <p className="text-xs text-gray-400">Maximum 50 MB per file</p>
                                    </div>
                                    <input
                                        ref={fileInputRef}
                                        type="file"
                                        multiple
                                        className="hidden"
                                        onChange={onFileInputChange}
                                    />

                                    {attachments.length > 0 && (
                                        <div className="mt-2">
                                            <ul className="divide-y border rounded">
                                                {attachments.map((f, idx) => (
                                                    <li key={idx} className="px-3 py-2 flex items-center justify-between text-sm">
                                                        <div className="truncate pr-4">
                                                            <div className="font-medium truncate">{f.name}</div>
                                                            <div className="text-xs text-gray-500">{(f.size/1024).toFixed(1)} KB</div>
                                                        </div>
                                                        <div>
                                                            <button type="button" onClick={() => removeAttachment(idx)} className="text-red-500 text-xs">Remove</button>
                                                        </div>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    )}
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Date</label>
                                    <input type="date" className="ti-form-input" value={form.communication_date}
                                           onChange={e => setForm({...form, communication_date: e.target.value})}/>
                                </div>
                            </div>

                            <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                                <button type="button" className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors" onClick={() => setCreateOpen(false)}>Cancel</button>
                                <button type="submit" className="flex items-center gap-1.5 px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-60 transition-colors font-medium" disabled={saving}>{saving ? 'Saving...' : 'Create'}</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {active && (
                <div role="dialog" aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-auto">
                        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                            <h3 className="text-base font-semibold text-gray-800">Communication #{active.id}</h3>
                            <button
                                type="button"
                                className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
                                onClick={() => setActive(null)}
                                aria-label="Close"
                            >
                                <i className="ri ri-close-line text-lg"></i>
                            </button>
                        </div>

                        <div className="px-5 py-5 space-y-4">
                            <p><strong>Client:</strong> {active.client?.name}</p>
                            <p><strong>Type:</strong> {active.type}</p>
                            <p><strong>Subject:</strong> {active.subject}</p>
                            <p className="mt-3"><strong>Content</strong></p>
                            <div className="prose max-w-none">{active.content ?? '-'}</div>
                            {active.attachments && active.attachments.length > 0 && (
                                <div className="mt-4">
                                    <p className="font-semibold">Attachments</p>
                                    <ul className="list-disc pl-5 mt-2">
                                        {active.attachments.map((a: any) => (
                                            <li key={a.id}>
                                                <a className="text-indigo-600" href={window.location.origin + '/storage/' + a.file_path} target="_blank" rel="noopener noreferrer">{a.file_name}</a>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            )}
                        </div>

                        <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                            <button onClick={() => setActive(null)} className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">Close</button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}
