﻿import { useEffect, useMemo, useState } from 'preact/hooks';
import ModalShell from '../ui/ModalShell';
import { formatWorkOrderDisplayCode } from '../../lib/displayIds';
import { getStatusLabel } from '../../stores/taskStore';
import { getTaskCraneDisplay, getTaskCraneOwner } from '../../lib/taskCraneDisplay';
import { updateVehicle, $vehicles } from '../../stores/fleetDashboardStore';

const STATUS_OPTIONS = ['aktivan', 'servis', 'spreman_za_zavrsetak', 'zavrsen', 'neaktivan'];

function todayIso() {
    return new Date().toISOString().slice(0, 10);
}

function formatDate(value) {
    if (!value) return '-';
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return value;
    return parsed.toLocaleDateString('hr-HR');
}

function formatDateTime(value) {
    if (!value) return '-';
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return '-';
    return parsed.toLocaleString('hr-HR');
}

function formatCost(value) {
    const numeric = Number(value);
    if (Number.isNaN(numeric)) return '-';
    return `${numeric.toFixed(2)} EUR`;
}

export default function TaskServiceRecordsModal({
    open,
    task,
    records = [],
    workOrders = [],
    onClose,
    onOpenServiceRecord,
    onAssignWorkOrder,
    onUpdateTask,
    onCreateServiceRecord,
    onSetServiceContext,
}) {
    const [showWorkOrderEditor, setShowWorkOrderEditor] = useState(false);
    const [selectedWorkOrderId, setSelectedWorkOrderId] = useState('');
    const [assigningWorkOrder, setAssigningWorkOrder] = useState(false);
    const [assignError, setAssignError] = useState('');
    const [showTaskEditor, setShowTaskEditor] = useState(false);
    const [updatingTask, setUpdatingTask] = useState(false);
    const [taskError, setTaskError] = useState('');
    const [taskForm, setTaskForm] = useState({
        title: '',
        description: '',
        status: 'aktivan',
        scheduled_date: '',
    });
    const [craneDataModalOpen, setCraneDataModalOpen] = useState(false);
    const [craneDataForm, setCraneDataForm] = useState({ superstructure_working_hours: '', chassis_working_hours: '', current_mileage: '' });
    const [savingCraneData, setSavingCraneData] = useState(false);
    const [craneDataError, setCraneDataError] = useState('');

    useEffect(() => {
        if (!open || typeof window === 'undefined') return;
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }, [open]);

    useEffect(() => {
        if (!task) return;
        setSelectedWorkOrderId(task.work_order ? String(task.work_order) : '');
        setShowWorkOrderEditor(!task.work_order);
        setAssignError('');
        setAssigningWorkOrder(false);
        setShowTaskEditor(false);
        setTaskError('');
        setUpdatingTask(false);
        setTaskForm({
            title: String(task.title || ''),
            description: String(task.description || ''),
            status: String(task.status || 'aktivan'),
            scheduled_date: String(task.scheduled_date || ''),
        });
        setCraneDataModalOpen(false);
        setCraneDataError('');
        setSavingCraneData(false);
    }, [task?.id, task?.work_order]);

    const openCraneDataModal = () => {
        const craneVehicleId = task?.vehicle;
        if (!craneVehicleId) return;
        const craneVehicle = ($vehicles?.get?.() || []).find((v) => String(v.id) === String(craneVehicleId)) || null;
        setCraneDataForm({
            superstructure_working_hours: String(craneVehicle?.superstructure_working_hours ?? ''),
            chassis_working_hours: String(craneVehicle?.chassis_working_hours ?? ''),
            current_mileage: String(craneVehicle?.current_mileage ?? ''),
        });
        setCraneDataError('');
        setCraneDataModalOpen(true);
    };

    const handleSaveCraneData = async () => {
        const craneVehicleId = task?.vehicle;
        if (!craneVehicleId) {
            setCraneDataError('Dizalica nije pronađena.');
            return;
        }
        const superstructure = craneDataForm.superstructure_working_hours === '' ? undefined : Number(craneDataForm.superstructure_working_hours);
        const chassis = craneDataForm.chassis_working_hours === '' ? undefined : Number(craneDataForm.chassis_working_hours);
        const mileage = craneDataForm.current_mileage === '' ? undefined : Number(craneDataForm.current_mileage);
        if (superstructure !== undefined && (Number.isNaN(superstructure) || superstructure < 0)) {
            setCraneDataError('Radni sati superstrukture moraju biti pozitivan broj.');
            return;
        }
        if (chassis !== undefined && (Number.isNaN(chassis) || chassis < 0)) {
            setCraneDataError('Radni sati podvozja moraju biti pozitivan broj.');
            return;
        }
        if (mileage !== undefined && (Number.isNaN(mileage) || mileage < 0)) {
            setCraneDataError('Kilometraža mora biti pozitivan broj.');
            return;
        }
        const payload = {};
        if (superstructure !== undefined) payload.superstructure_working_hours = superstructure;
        if (chassis !== undefined) payload.chassis_working_hours = chassis;
        if (mileage !== undefined) payload.current_mileage = mileage;
        if (Object.keys(payload).length === 0) {
            setCraneDataError('Nije unesena niti jedna vrijednost za ažuriranje.');
            return;
        }
        setSavingCraneData(true);
        setCraneDataError('');
        try {
            await updateVehicle(craneVehicleId, payload);
            setCraneDataModalOpen(false);
        } catch (err) {
            setCraneDataError(err?.message || 'Ažuriranje podataka dizalice nije uspjelo.');
        } finally {
            setSavingCraneData(false);
        }
    };

    const currentWorkOrder = useMemo(
        () => workOrders.find((item) => String(item.id) === String(task?.work_order || selectedWorkOrderId)) || null,
        [workOrders, task?.work_order, selectedWorkOrderId]
    );

    const sortedWorkOrders = useMemo(() => {
        const today = todayIso();
        return [...workOrders].sort((a, b) => {
            const aToday = String(a.date || '').slice(0, 10) === today ? 1 : 0;
            const bToday = String(b.date || '').slice(0, 10) === today ? 1 : 0;
            if (bToday !== aToday) return bToday - aToday;
            return String(b.date || '').localeCompare(String(a.date || ''));
        });
    }, [workOrders]);

    const effectiveWorkOrderId = task?.work_order ? String(task.work_order) : String(selectedWorkOrderId || '');

    const handleWorkOrderChange = async (event) => {
        const nextValue = String(event.currentTarget.value || '');
        setSelectedWorkOrderId(nextValue);
        setAssignError('');
        setAssigningWorkOrder(true);
        try {
            await onAssignWorkOrder?.(task, nextValue || null);
            setShowWorkOrderEditor(false);
        } catch (error) {
            setAssignError(error?.message || 'Neuspješno spremanje putnog naloga za radni zadatak.');
        } finally {
            setAssigningWorkOrder(false);
        }
    };

    const handleTaskUpdate = async (event) => {
        event.preventDefault();
        const title = String(taskForm.title || '').trim();
        const status = String(taskForm.status || 'aktivan');
        const description = String(taskForm.description || '').trim();
        if (!title) {
            setTaskError('Naslov zadatka je obavezan.');
            return;
        }
        if ((status === 'zavrsen' || status === 'neaktivan') && !effectiveWorkOrderId) {
            setTaskError('Putni nalog je obavezan prije zatvaranja zadatka.');
            return;
        }
        setTaskError('');
        setUpdatingTask(true);
        try {
            await onUpdateTask?.(task, {
                title,
                description,
                status,
                    scheduled_date: taskForm.scheduled_date || null,
                });
            setShowTaskEditor(false);
        } catch (error) {
            const conflictCode = error?.details?.code;
            if (error?.status === 409 && conflictCode === 'OPEN_WORK_ORDER_BLOCKING_TASK_CLOSE') {
                const confirmText = error?.details?.message || error?.message || 'Povezani putni nalog je još otvoren. Želite li ga automatski zatvoriti?';
                const approved = typeof window !== 'undefined' ? window.confirm(confirmText) : false;
                if (approved) {
                    try {
                        await onUpdateTask?.(task, {
                            title,
                            description,
                            status,
                            scheduled_date: taskForm.scheduled_date || null,
                            auto_close_work_order: true,
                        });
                        setShowTaskEditor(false);
                        return;
                    } catch (retryError) {
                        setTaskError(retryError?.message || 'Neuspješno automatsko zatvaranje putnog naloga i završetak zadatka.');
                        return;
                    }
                }
                setTaskError(confirmText);
                return;
            }
            setTaskError(error?.message || 'Neuspješno spremanje izmjena radnog zadatka.');
        } finally {
            setUpdatingTask(false);
        }
    };

    if (!open || !task) return null;

    return (
        <>
        <ModalShell
            onClose={onClose}
            overlayClassName="z-50 overflow-y-auto p-4 pt-2"
            contentClassName="flex items-start justify-center min-h-full"
            panelClassName="w-full max-w-4xl rounded-xl border border-border-hairline bg-canvas-elevated shadow-xl max-h-[calc(100vh-6rem)] overflow-hidden"
        >
            <div className="w-full flex flex-col h-full">
                    <div className="flex items-center justify-between border-b border-border-hairline px-5 py-4">
                        <div>
                            <h3 className="text-lg font-semibold text-text-main">Radni zadatak detalji</h3>
                            <p className="text-xs text-text-muted">
                                Radni zadatak: {task.title || '-'} • Status: {getStatusLabel(task.status || '-')} • Zapisa: {records.length}
                            </p>
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                type="button"
                                onClick={() => onSetServiceContext?.(task)}
                                className="btn-erp rounded-md bg-emerald-600 px-3 py-1 text-xs font-semibold normal-case tracking-normal text-white hover:bg-emerald-700"
                            >
                                Postavi servisni kontekst
                            </button>
                            {task?.vehicle && (
                                <button
                                    type="button"
                                    onClick={openCraneDataModal}
                                    className="rounded-md border border-border-hairline px-3 py-1 text-xs font-semibold text-text-main hover:bg-canvas-base"
                                >
                                    Uredi podatke dizalice
                                </button>
                            )}
                            <button
                                type="button"
                                onClick={onClose}
                                className="rounded-md px-2 py-1 text-sm text-text-muted hover:bg-canvas-deep"
                                aria-label="Zatvori"
                            >
                                ✕
                            </button>
                        </div>
                    </div>

                    <div className="max-h-[calc(100vh-12rem)] overflow-y-auto p-4">
                        <div className="space-y-4">
                            <div className="rounded-lg border border-border-hairline bg-canvas-base p-3">
                                <div className="mb-2 flex items-center justify-between gap-2">
                                    <h4 className="text-sm font-semibold text-text-main">Podaci radnog zadatka</h4>
                                    {!showTaskEditor ? (
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setTaskError('');
                                                setShowTaskEditor(true);
                                            }}
                                            className="rounded border border-border-hairline px-2 py-1 text-xs text-text-main hover:bg-canvas-base"
                                        >
                                            Izmijeni radni zadatak
                                        </button>
                                    ) : null}
                                </div>
                                {!showTaskEditor ? (
                                    <dl className="grid gap-2 text-sm sm:grid-cols-2">
                                        <div>
                                            <dt className="text-xs text-text-muted">Naslov</dt>
                                            <dd className="text-text-main">{task.title || '-'}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Status</dt>
                                            <dd className="text-text-main">{getStatusLabel(task.status || '-')}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Dodijeljeno</dt>
                                            <dd className="text-text-main">{task.assigned_to_name || '-'}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Vlasnik</dt>
                                            <dd className="text-text-main">{getTaskCraneOwner(task)}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Dizalica</dt>
                                            <dd className="flex items-center gap-2 text-text-main">
                                                <span>{getTaskCraneDisplay(task)}</span>
                                                {task?.vehicle && (
                                                    <button
                                                        type="button"
                                                        onClick={openCraneDataModal}
                                                        className="rounded border border-border-hairline px-2 py-1 text-xs text-text-main hover:bg-canvas-base"
                                                        title="Izmijeni radne sate i kilometrazu dizalice"
                                                    >
                                                        Uredi podatke
                                                    </button>
                                                )}
                                            </dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Putni nalog</dt>
                                            <dd className="text-text-main">{task.work_order_label || '-'}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Planirani datum</dt>
                                            <dd className="text-text-main">{task.scheduled_date ? formatDate(task.scheduled_date) : '-'}</dd>
                                        </div>
                                        <div>
                                            <dt className="text-xs text-text-muted">Vrijeme izrade</dt>
                                            <dd className="text-text-main">{formatDateTime(task.created_at)}</dd>
                                        </div>
                                        <div className="sm:col-span-2">
                                            <dt className="text-xs text-text-muted">Opis</dt>
                                            <dd className="whitespace-pre-wrap text-text-main">{task.description || '-'}</dd>
                                        </div>
                                    </dl>
                                ) : (
                                    <form onSubmit={handleTaskUpdate} className="space-y-3">
                                        <label className="flex flex-col gap-1 text-sm">
                                            <span className="text-xs text-text-muted">Naslov *</span>
                                            <input
                                                type="text"
                                                value={taskForm.title}
                                                onInput={(event) => setTaskForm((prev) => ({ ...prev, title: event.currentTarget.value }))}
                                                disabled={updatingTask}
                                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                                required
                                            />
                                        </label>
                                        <label className="flex flex-col gap-1 text-sm">
                                            <span className="text-xs text-text-muted">Opis</span>
                                            <textarea
                                                rows={3}
                                                value={taskForm.description}
                                                onInput={(event) => setTaskForm((prev) => ({ ...prev, description: event.currentTarget.value }))}
                                                disabled={updatingTask}
                                                className="resize-none rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                            />
                                        </label>
                                        <div className="grid gap-3 sm:grid-cols-2">
                                            <label className="flex flex-col gap-1 text-sm">
                                                <span className="text-xs text-text-muted">Vlasnik</span>
                                                <input
                                                    type="text"
                                                    value={getTaskCraneOwner(task)}
                                                    disabled
                                                    className="rounded-lg border border-border-hairline bg-canvas-deep px-3 py-2 text-text-main disabled:opacity-80"
                                                />
                                            </label>
                                            <label className="flex flex-col gap-1 text-sm">
                                                <span className="text-xs text-text-muted">Dizalica</span>
                                                <input
                                                    type="text"
                                                    value={getTaskCraneDisplay(task)}
                                                    disabled
                                                    className="rounded-lg border border-border-hairline bg-canvas-deep px-3 py-2 text-text-main disabled:opacity-80"
                                                />
                                            </label>
                                        </div>
                                        <label className="flex flex-col gap-1 text-sm">
                                            <span className="text-xs text-text-muted">Status</span>
                                            <select
                                                value={taskForm.status}
                                                onChange={(event) => setTaskForm((prev) => ({ ...prev, status: event.currentTarget.value }))}
                                                disabled={updatingTask}
                                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                            >
                                                {STATUS_OPTIONS.map((status) => (
                                                    <option key={status} value={status}>
                                                        {getStatusLabel(status)}
                                                    </option>
                                                ))}
                                            </select>
                                        </label>
                                        <label className="flex flex-col gap-1 text-sm">
                                            <span className="text-xs text-text-muted">Planirani datum izvršenja</span>
                                            <input
                                                type="date"
                                                value={taskForm.scheduled_date || ''}
                                                onInput={(event) => setTaskForm((prev) => ({ ...prev, scheduled_date: event.currentTarget.value }))}
                                                disabled={updatingTask}
                                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                            />
                                        </label>
                                        {taskError ? (
                                            <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                                                {taskError}
                                            </div>
                                        ) : null}
                                        <div className="flex justify-end gap-2">
                                            <button
                                                type="button"
                                                onClick={() => {
                                                    setTaskError('');
                                                    setShowTaskEditor(false);
                                                    setTaskForm({
                                                        title: String(task.title || ''),
                                                        description: String(task.description || ''),
                                                        status: String(task.status || 'aktivan'),
                                                        scheduled_date: String(task.scheduled_date || ''),
                                                    });
                                                }}
                                                disabled={updatingTask}
                                                className="rounded border border-border-hairline px-3 py-1.5 text-xs text-text-main hover:bg-canvas-elevated disabled:opacity-60"
                                            >
                                                Odustani
                                            </button>
                                            <button
                                                type="submit"
                                                disabled={updatingTask}
                                                className="rounded bg-indigo-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-indigo-700 disabled:opacity-60"
                                            >
                                                {updatingTask ? 'Spremanje...' : 'Spremi izmjene'}
                                            </button>
                                        </div>
                                    </form>
                                )}
                            </div>

                            <div className="rounded-lg border border-border-hairline bg-canvas-base p-3">
                                <h4 className="mb-2 text-sm font-semibold text-text-main">Putni nalozi</h4>
                                {currentWorkOrder && !showWorkOrderEditor ? (
                                    <div className="flex flex-wrap items-center justify-between gap-2 rounded border border-border-hairline bg-canvas-elevated px-3 py-2">
                                        <p className="text-sm text-text-main">
                                            {formatWorkOrderDisplayCode(currentWorkOrder)} • {formatDate(currentWorkOrder.date)} • {currentWorkOrder.craneLabel || currentWorkOrder.craneInfo?.registration_number || '-'} • {currentWorkOrder.status || '-'}
                                        </p>
                                        <button
                                            type="button"
                                            onClick={() => setShowWorkOrderEditor(true)}
                                            className="rounded border border-border-hairline px-2 py-1 text-xs text-text-main hover:bg-canvas-base"
                                        >
                                            Izmijeni putni nalog
                                        </button>
                                    </div>
                                ) : (
                                    <div className="space-y-2">
                                        <select
                                            value={selectedWorkOrderId}
                                            onChange={handleWorkOrderChange}
                                            disabled={assigningWorkOrder}
                                            className="w-full rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-sm text-text-main disabled:opacity-60"
                                        >
                                            <option value="">— Odaberi putni nalog —</option>
                                            {sortedWorkOrders.map((workOrder) => {
                                                const isToday = String(workOrder.date || '').slice(0, 10) === todayIso();
                                                return (
                                                    <option key={workOrder.id} value={String(workOrder.id)}>
                                                        {isToday ? '★ ' : ''}{formatWorkOrderDisplayCode(workOrder)} • {formatDate(workOrder.date)} • {workOrder.craneLabel || workOrder.craneInfo?.registration_number || '-'} • {workOrder.status || '-'}
                                                    </option>
                                                );
                                            })}
                                        </select>
                                        <p className="text-xs text-text-muted">
                                            {assigningWorkOrder
                                                ? 'Spremanje odabira putnog naloga...'
                                                : 'Isti putni nalog možete dodijeliti više zadataka. Danas (★) su prikazani prvo.'}
                                        </p>
                                    </div>
                                )}
                                {assignError && (
                                    <div className="mt-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                                        {assignError}
                                    </div>
                                )}
                            </div>

                            <div className="rounded-lg border border-border-hairline bg-canvas-base p-3">
                                <div className="mb-2 flex items-center justify-between gap-2">
                                    <h4 className="text-sm font-semibold text-text-main">Povezani servisni zapisi</h4>
                                    <button
                                        type="button"
                                        onClick={() => onCreateServiceRecord?.(task)}
                                        className="rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700"
                                    >
                                        + Servisni zapis
                                    </button>
                                </div>
                                {records.length === 0 ? (
                                    <div className="rounded-lg border border-border-hairline bg-canvas-elevated px-4 py-3 text-sm text-text-muted">
                                        Nema povezanih servisnih zapisa za odabrani radni zadatak.
                                    </div>
                                ) : (
                                    <div className="overflow-hidden rounded-lg border border-border-hairline">
                                        <table className="w-full table-auto text-sm">
                                            <thead className="bg-canvas-base text-left text-text-muted">
                                                <tr>
                                                    <th className="px-3 py-2">Datum</th>
                                                    <th className="px-3 py-2">Opis</th>
                                                    <th className="px-3 py-2">Trošak</th>
                                                    <th className="px-3 py-2">Datoteke</th>
                                                    <th className="px-3 py-2">Akcija</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {records.map((record) => (
                                                    <tr key={record.id} className="border-t border-border-hairline">
                                                        <td className="px-3 py-2">{formatDate(record.service_date)}</td>
                                                        <td className="max-w-[420px] truncate px-3 py-2" title={record.description || ''}>
                                                            {record.description || '-'}
                                                        </td>
                                                        <td className="px-3 py-2">{formatCost(record.cost)}</td>
                                                        <td className="px-3 py-2">{record.files_count ?? (record.photos_count ?? 0)}</td>
                                                        <td className="px-3 py-2">
                                                            <button
                                                                type="button"
                                                                onClick={() => onOpenServiceRecord?.(record)}
                                                                className="rounded border border-border-hairline px-2 py-1 text-xs text-text-main hover:bg-canvas-base"
                                                            >
                                                                Detalji
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </ModalShell>

            {craneDataModalOpen && (
                <ModalShell
                    onClose={() => setCraneDataModalOpen(false)}
                    overlayClassName="z-[60] bg-black/40 p-4"
                    contentClassName="flex min-h-full items-center justify-center"
                    panelClassName="w-full max-w-lg rounded-xl border border-border-hairline bg-canvas-elevated shadow-2xl"
                >
                    <div className="p-4 space-y-4">
                        <p className="text-sm text-text-muted">
                            Ažurirajte radne sate i kilometražu za dizalicu: <strong>{getTaskCraneDisplay(task)}</strong>
                        </p>
                        <label className="flex flex-col gap-1 text-sm">
                            <span className="text-xs text-text-muted">Radni sati superstrukture</span>
                            <input
                                type="number"
                                min="0"
                                step="0.01"
                                value={craneDataForm.superstructure_working_hours}
                                onInput={(e) => setCraneDataForm((p) => ({ ...p, superstructure_working_hours: e.currentTarget.value }))}
                                disabled={savingCraneData}
                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                placeholder="npr. 1250.5"
                            />
                        </label>
                        <label className="flex flex-col gap-1 text-sm">
                            <span className="text-xs text-text-muted">Radni sati podvozja</span>
                            <input
                                type="number"
                                min="0"
                                step="0.01"
                                value={craneDataForm.chassis_working_hours}
                                onInput={(e) => setCraneDataForm((p) => ({ ...p, chassis_working_hours: e.currentTarget.value }))}
                                disabled={savingCraneData}
                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                placeholder="npr. 980.0"
                            />
                        </label>
                        <label className="flex flex-col gap-1 text-sm">
                            <span className="text-xs text-text-muted">Trenutna kilometraža (km)</span>
                            <input
                                type="number"
                                min="0"
                                step="1"
                                value={craneDataForm.current_mileage}
                                onInput={(e) => setCraneDataForm((p) => ({ ...p, current_mileage: e.currentTarget.value }))}
                                disabled={savingCraneData}
                                className="rounded-lg border border-border-hairline bg-canvas-elevated px-3 py-2 text-text-main disabled:opacity-60"
                                placeholder="npr. 45000"
                            />
                        </label>
                        {craneDataError && (
                            <p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{craneDataError}</p>
                        )}
                        <div className="flex justify-end gap-2">
                            <button
                                type="button"
                                onClick={() => setCraneDataModalOpen(false)}
                                disabled={savingCraneData}
                                className="rounded-lg border border-border-hairline px-4 py-2 text-sm text-text-main hover:bg-canvas-base disabled:opacity-50"
                            >
                                Odustani
                            </button>
                            <button
                                type="button"
                                onClick={handleSaveCraneData}
                                disabled={savingCraneData}
                                className="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700 disabled:opacity-50"
                            >
                                {savingCraneData ? 'Spremam…' : 'Spremi podatke'}
                            </button>
                        </div>
                    </div>
                </ModalShell>
            )}
        </>
    );
}
