import { useMemo, useState } from 'preact/hooks';
import LeftSlideDrawer from './LeftSlideDrawer';

function formatDate(value) {
    if (!value) return '-';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return '-';
    return new Intl.DateTimeFormat('hr-HR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
    }).format(date);
}

function workOrderLabel(item) {
    const code = String(item?.display_code || '').trim().toUpperCase();
    if (code) return code;
    return `WO-${String(item?.id || '').slice(0, 8)}`;
}

export default function ServiceNotesWidget({
    notes = [],
    loading = false,
    canManageRecipients = false,
    activeTasks = [],
    activeWorkOrders = [],
    teamMembers = [],
    onCreate,
    onClose,
}) {
    const [note, setNote] = useState('');
    const [noteDate, setNoteDate] = useState('');
    const [audience, setAudience] = useState('self');
    const [targetUsers, setTargetUsers] = useState([]);
    const [contextType, setContextType] = useState('none');
    const [contextValue, setContextValue] = useState('');
    const [submitting, setSubmitting] = useState(false);

    const undatedNotes = useMemo(
        () => notes.filter((item) => !item.note_date),
        [notes]
    );
    const datedNotes = useMemo(
        () => notes.filter((item) => !!item.note_date),
        [notes]
    );

    async function handleSubmit(event) {
        event.preventDefault();
        if (!String(note || '').trim()) return;
        const payload = {
            note: String(note || '').trim(),
            note_date: noteDate || null,
            audience,
        };
        if (audience === 'member' && targetUsers.length > 0) {
            payload.target_users = targetUsers;
        }
        if (contextType === 'work_order' && contextValue) {
            payload.work_order = contextValue;
        }
        if (contextType === 'task' && contextValue) {
            payload.task = contextValue;
        }
        setSubmitting(true);
        try {
            await onCreate?.(payload);
            setNote('');
            setNoteDate('');
            setContextType('none');
            setContextValue('');
            setAudience('self');
            setTargetUsers([]);
        } finally {
            setSubmitting(false);
        }
    }

    return (
        <LeftSlideDrawer
            drawerId="notes"
            title="🗒️ Bilješke"
            tabLabel="🗒️ Bilješke"
            tabTitle="Bilješke"
            tabTopClassName="top-[calc(50%+96px)]"
            backdropClassName="z-[48]"
            panelClassName="z-[49]"
            tabClassName="z-[50]"
        >
            <p className="border-b border-border-hairline px-4 py-2 text-[11px] text-text-muted">
                Bilješke i podsjetnici u servisnom kontekstu
            </p>

            <form onSubmit={handleSubmit} className="space-y-2 border-b border-border-hairline px-4 py-3">
                <textarea
                    value={note}
                    onInput={(event) => setNote(event.currentTarget.value)}
                    className="h-16 w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                    placeholder="Upiši bilješku..."
                    required
                />
                <input
                    type="date"
                    value={noteDate}
                    onInput={(event) => setNoteDate(event.currentTarget.value)}
                    className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                />
                <select
                    value={contextType}
                    onChange={(event) => {
                        setContextType(event.currentTarget.value);
                        setContextValue('');
                    }}
                    className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                >
                    <option value="none">Bez vezanog naloga/zadatka</option>
                    <option value="work_order">Aktivni putni nalog</option>
                    <option value="task">Aktivni radni zadatak</option>
                </select>
                {contextType === 'work_order' && (
                    <select
                        value={contextValue}
                        onChange={(event) => setContextValue(event.currentTarget.value)}
                        className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                    >
                        <option value="">Odaberi putni nalog</option>
                        {activeWorkOrders.map((item) => (
                            <option key={item.id} value={item.id}>
                                {workOrderLabel(item)}
                            </option>
                        ))}
                    </select>
                )}
                {contextType === 'task' && (
                    <select
                        value={contextValue}
                        onChange={(event) => setContextValue(event.currentTarget.value)}
                        className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                    >
                        <option value="">Odaberi radni zadatak</option>
                        {activeTasks.map((item) => (
                            <option key={item.id} value={item.id}>
                                {item.title || `Task ${String(item.id).slice(0, 8)}`}
                            </option>
                        ))}
                    </select>
                )}
                <select
                    value={audience}
                    onChange={(event) => {
                        setAudience(event.currentTarget.value);
                        if (event.currentTarget.value !== 'member') {
                            setTargetUsers([]);
                        }
                    }}
                    className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                >
                    <option value="self">Notifikacija samo meni</option>
                    {canManageRecipients && <option value="member">Notifikacija odabranim članovima tima</option>}
                    {canManageRecipients && <option value="team">Notifikacija svim članovima tima</option>}
                </select>
                {canManageRecipients && audience === 'member' && (
                    <select
                        multiple
                        value={targetUsers}
                        onChange={(event) => {
                            const selected = Array.from(event.currentTarget.selectedOptions).map((option) => option.value);
                            setTargetUsers(selected);
                        }}
                        size={Math.min(6, Math.max(3, teamMembers.length || 3))}
                        className="w-full rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5 text-xs text-text-main"
                    >
                        {teamMembers.map((member) => (
                            <option key={member.id} value={member.id}>
                                {member.full_name || member.email}
                            </option>
                        ))}
                    </select>
                )}
                {canManageRecipients && audience === 'member' && (
                    <p className="text-[10px] text-text-muted">
                        Držite Ctrl (ili Cmd) za odabir više članova tima.
                    </p>
                )}
                <button
                    type="submit"
                    disabled={submitting}
                    className="w-full rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-indigo-700 disabled:opacity-60"
                >
                    {submitting ? 'Spremanje...' : 'Spremi bilješku'}
                </button>
            </form>

            <div className="flex-1 overflow-y-auto px-4 py-3">
                {loading && <p className="text-xs text-text-muted">Učitavanje bilješki...</p>}
                {!loading && undatedNotes.length === 0 && datedNotes.length === 0 && (
                    <p className="text-xs text-text-muted">Nema aktivnih bilješki.</p>
                )}

                {undatedNotes.length > 0 && (
                    <div className="mb-3">
                        <p className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-violet-700">Bez datuma (permanentno)</p>
                        <ul className="space-y-1.5">
                            {undatedNotes.map((item) => (
                                <li key={item.id} className="rounded-md border border-violet-200 bg-violet-50 px-2 py-1.5">
                                    <p className="text-xs text-violet-900">{item.note}</p>
                                    <div className="mt-1 flex items-center justify-between">
                                        <span className="text-[10px] text-violet-700">{item.task_title || item.work_order_label || 'Općenito'}</span>
                                        <button
                                            type="button"
                                            onClick={() => onClose?.(item.id)}
                                            className="text-[10px] font-semibold text-violet-700 hover:text-violet-900"
                                        >
                                            Zatvori
                                        </button>
                                    </div>
                                </li>
                            ))}
                        </ul>
                    </div>
                )}

                {datedNotes.length > 0 && (
                    <div>
                        <p className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-muted">Podsjetnici</p>
                        <ul className="space-y-1.5">
                            {datedNotes.map((item) => (
                                <li key={item.id} className="rounded-md border border-border-hairline bg-canvas-base px-2 py-1.5">
                                    <p className="text-xs text-text-main">{item.note}</p>
                                    <div className="mt-1 flex items-center justify-between text-[10px] text-text-muted">
                                        <span>{formatDate(item.note_date)}</span>
                                        <button
                                            type="button"
                                            onClick={() => onClose?.(item.id)}
                                            className="font-semibold text-indigo-600 hover:text-indigo-800"
                                        >
                                            Zatvori
                                        </button>
                                    </div>
                                </li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>
        </LeftSlideDrawer>
    );
}
