import { useState, useEffect, useCallback } from 'react';
import { Link, router } from '@inertiajs/react';
import WorkshopLayout from '@/Layouts/WorkshopLayout';

// ── Status config ─────────────────────────────────────────────────────────────

const STATUS_BADGE = {
    open:               { label: 'Open',              bg: 'bg-blue-50',   text: 'text-blue-700',   border: 'border-blue-100'  },
    in_progress:        { label: 'In Progress',        bg: 'bg-amber-50',  text: 'text-amber-700',  border: 'border-amber-100' },
    awaiting_approval:  { label: 'Awaiting Approval',  bg: 'bg-purple-50', text: 'text-purple-700', border: 'border-purple-100'},
    approved:           { label: 'Approved',            bg: 'bg-green-50',  text: 'text-green-700',  border: 'border-green-100' },
    draft:              { label: 'Draft',               bg: 'bg-gray-50',   text: 'text-gray-500',   border: 'border-gray-100'  },
};

const SECTION_STATUS = {
    open:             { bg: 'bg-gray-100',   text: 'text-gray-600'   },
    pending_approval: { bg: 'bg-amber-100',  text: 'text-amber-700'  },
    approved:         { bg: 'bg-blue-100',   text: 'text-blue-700'   },
    paid:             { bg: 'bg-green-100',  text: 'text-green-700'  },
};

// ── Icons ─────────────────────────────────────────────────────────────────────

const ClockIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <circle cx="12" cy="12" r="10" strokeWidth="2"/>
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6l4 2"/>
    </svg>
);

const CarIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2"
            d="M5 17H3a2 2 0 01-2-2v-4l2-5h14l2 5v4a2 2 0 01-2 2h-2M9 17a2 2 0 104 0 2 2 0 00-4 0z"/>
    </svg>
);

const PlayIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24">
        <path d="M8 5v14l11-7z"/>
    </svg>
);

const StopIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="currentColor" viewBox="0 0 24 24">
        <rect x="6" y="6" width="12" height="12" rx="1"/>
    </svg>
);

const PlusIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"/>
    </svg>
);

const UserIcon = ({ className = 'w-4 h-4' }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2"
            d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
    </svg>
);

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatTime(totalSeconds) {
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;
    if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
    return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

function HourBar({ logged, quoted }) {
    if (!quoted) return null;
    const pct  = Math.min((logged / quoted) * 100, 120);
    const over = logged > quoted;
    return (
        <div className="w-full h-1.5 bg-gray-100 rounded-full overflow-hidden mt-1.5">
            <div className={`h-full rounded-full ${over ? 'bg-red-400' : 'bg-green-400'}`}
                 style={{ width: `${Math.min(pct, 100)}%` }} />
        </div>
    );
}

// ── Global clock state manager ─────────────────────────────────────────────────

function useJobClock(initialClock) {
    const [activeClock, setActiveClock] = useState(initialClock);
    const [elapsed, setElapsed]         = useState(initialClock?.elapsed_seconds ?? 0);
    const [loading, setLoading]         = useState(false);

    // Tick every second when a clock is running
    useEffect(() => {
        if (!activeClock) { setElapsed(0); return; }
        setElapsed(activeClock.elapsed_seconds);
        const id = setInterval(() => setElapsed(e => e + 1), 1000);
        return () => clearInterval(id);
    }, [activeClock?.clock_id]);

    const clockOn = useCallback(async (jobCardId, sectionId = null) => {
        setLoading(true);
        try {
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            const res = await fetch('/clock/start', {
                method:  'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body:    JSON.stringify({ job_card_id: jobCardId, section_id: sectionId }),
            });
            const data = await res.json();
            if (data.ok) {
                setActiveClock({
                    clock_id:        data.clock_id,
                    job_card_id:     data.job_card_id,
                    section_id:      data.section_id,
                    started_at:      data.started_at,
                    elapsed_seconds: 0,
                });
                setElapsed(0);
            }
        } finally {
            setLoading(false);
        }
    }, []);

    const clockOff = useCallback(async (createLog = true) => {
        if (!activeClock) return;
        setLoading(true);
        try {
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            const res = await fetch('/clock/stop', {
                method:  'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body:    JSON.stringify({ clock_id: activeClock.clock_id, create_log: createLog }),
            });
            const data = await res.json();
            if (data.ok) {
                setActiveClock(null);
                setElapsed(0);
                // Reload to refresh logged hours on cards
                router.reload({ only: ['jobCards', 'activeClock'] });
            }
        } finally {
            setLoading(false);
        }
    }, [activeClock]);

    return { activeClock, elapsed, loading, clockOn, clockOff };
}

// ── Live clock banner ─────────────────────────────────────────────────────────

function ClockBanner({ activeClock, elapsed, loading, onStop, jobCards }) {
    if (!activeClock) return null;

    const card    = jobCards.find(c => c.id === activeClock.job_card_id);
    const section = card?.sections.find(s => s.id === activeClock.section_id);
    const label   = section ? `${card?.vehicle_description} — ${section.name}`
                             : (card?.vehicle_description ?? `Job #${activeClock.job_card_id}`);

    return (
        <div className="fixed bottom-0 left-0 right-0 z-50 flex items-center justify-between gap-4
            bg-gray-900 text-white px-6 py-4 shadow-2xl border-t-2 border-green-500">
            <div className="flex items-center gap-3">
                {/* Pulsing green dot */}
                <span className="relative flex h-3 w-3">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
                    <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500" />
                </span>
                <div>
                    <div className="text-xs text-gray-400 uppercase tracking-wider">Clocked On</div>
                    <div className="font-semibold text-sm truncate max-w-[240px]">{label}</div>
                </div>
            </div>

            <div className="text-2xl font-bold font-mono tracking-widest" style={{ fontFamily: 'JetBrains Mono, monospace' }}>
                {formatTime(elapsed)}
            </div>

            <div className="flex items-center gap-2">
                <button
                    onClick={() => onStop(true)}
                    disabled={loading}
                    className="flex items-center gap-2 px-4 py-2 rounded-xl bg-green-600 hover:bg-green-700 text-sm font-semibold transition-colors disabled:opacity-60"
                >
                    <StopIcon className="w-4 h-4" />
                    Stop &amp; Log
                </button>
                <button
                    onClick={() => onStop(false)}
                    disabled={loading}
                    className="flex items-center gap-2 px-3 py-2 rounded-xl bg-gray-700 hover:bg-gray-600 text-sm font-medium transition-colors disabled:opacity-60"
                >
                    Stop only
                </button>
            </div>
        </div>
    );
}

// ── Section pill with clock button ────────────────────────────────────────────

function SectionPill({ section, activeClock, onClockOn, onClockOff, loading }) {
    const cfg     = SECTION_STATUS[section.status] ?? { bg: 'bg-gray-100', text: 'text-gray-600' };
    const over    = section.quoted_hours > 0 && section.logged_hours > section.quoted_hours;

    const isClocked = activeClock?.section_id === section.id ||
                      (!activeClock?.section_id && activeClock?.job_card_id === section.job_card_id && !section.id);

    return (
        <div className={`rounded-xl border text-xs transition-all ${
            isClocked
                ? 'border-green-300 bg-green-50 ring-1 ring-green-300'
                : section.is_mine
                    ? 'border-blue-100 bg-blue-50'
                    : `border-transparent ${cfg.bg}`
        }`}>
            <div className="px-3 py-2">
                <div className={`font-semibold flex items-center gap-1.5 ${isClocked ? 'text-green-800' : cfg.text}`}>
                    {section.is_mine && !isClocked && (
                        <span className="w-1.5 h-1.5 rounded-full bg-blue-500 inline-block shrink-0" />
                    )}
                    {isClocked && (
                        <span className="relative flex h-2 w-2 shrink-0">
                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
                            <span className="relative inline-flex h-2 w-2 rounded-full bg-green-500" />
                        </span>
                    )}
                    <span className="truncate">{section.name}</span>
                </div>

                {section.assigned_to_name && (
                    <div className="flex items-center gap-1 mt-0.5 text-gray-500">
                        <UserIcon className="w-3 h-3 shrink-0" />
                        <span className="truncate">{section.assigned_to_name}</span>
                    </div>
                )}

                {section.quoted_hours > 0 && (
                    <>
                        <div className={`mt-1 font-mono ${over ? 'text-red-600 font-bold' : 'text-gray-500'}`}>
                            {section.logged_hours.toFixed(1)}h / {section.quoted_hours.toFixed(1)}h
                        </div>
                        <HourBar logged={section.logged_hours} quoted={section.quoted_hours} />
                    </>
                )}
            </div>

            {/* Clock button — only show for mechanic's own sections */}
            {section.is_mine && (
                <div className="px-3 pb-2">
                    {isClocked ? (
                        <button
                            onClick={() => onClockOff(true)}
                            disabled={loading}
                            className="w-full flex items-center justify-center gap-1.5 py-1.5 rounded-lg
                                bg-red-500 hover:bg-red-600 text-white text-xs font-bold transition-colors disabled:opacity-60"
                        >
                            <StopIcon className="w-3 h-3" />
                            Stop &amp; Log
                        </button>
                    ) : (
                        <button
                            onClick={() => onClockOn(section.job_card_id, section.id)}
                            disabled={loading}
                            className="w-full flex items-center justify-center gap-1.5 py-1.5 rounded-lg
                                bg-green-600 hover:bg-green-700 text-white text-xs font-bold transition-colors disabled:opacity-60"
                        >
                            <PlayIcon className="w-3 h-3" />
                            Clock On
                        </button>
                    )}
                </div>
            )}
        </div>
    );
}

// ── Job card tile ─────────────────────────────────────────────────────────────

function JobCardTile({ card, activeClock, onClockOn, onClockOff, loading }) {
    const cfg        = STATUS_BADGE[card.status] ?? { bg: 'bg-gray-50', text: 'text-gray-500', border: 'border-gray-100', label: card.status };
    const totalOver  = card.quoted_hours > 0 && card.logged_hours > card.quoted_hours;
    const hasMyWork  = card.sections.some(s => s.is_mine);
    const isActive   = activeClock?.job_card_id === card.id;

    return (
        <div className={`bg-white border rounded-2xl shadow-sm hover:shadow-md transition-all flex flex-col ${
            isActive ? 'border-green-300 ring-1 ring-green-200 shadow-green-100' :
            hasMyWork ? 'border-blue-100' : 'border-gray-200'
        }`}>
            {/* Header */}
            <div className="px-5 pt-5 pb-3 border-b border-gray-100">
                <div className="flex items-start justify-between gap-2 mb-2">
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-1.5 mb-0.5">
                            <CarIcon className="w-4 h-4 text-gray-400 shrink-0" />
                            <h3 className="font-bold text-gray-900 text-sm leading-tight truncate"
                                style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
                                {card.vehicle_description || 'Vehicle'}
                            </h3>
                        </div>
                        {card.vehicle_registration && (
                            <span className="inline-block text-xs font-mono bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
                                {card.vehicle_registration}
                            </span>
                        )}
                    </div>
                    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border shrink-0 ${cfg.bg} ${cfg.text} ${cfg.border}`}>
                        {cfg.label}
                    </span>
                </div>
                <p className="text-xs text-gray-500 truncate">{card.display_name}</p>
            </div>

            {/* Hours summary */}
            {card.quoted_hours > 0 && (
                <div className="px-5 py-2.5 border-b border-gray-100">
                    <div className="flex items-center justify-between text-xs mb-1">
                        <span className="text-gray-400 flex items-center gap-1">
                            <ClockIcon className="w-3 h-3" />
                            Labour hours
                        </span>
                        <span className={`font-mono font-semibold ${totalOver ? 'text-red-600' : 'text-gray-700'}`}>
                            {card.logged_hours.toFixed(1)} / {card.quoted_hours.toFixed(1)}h
                            {totalOver && <span className="ml-1 text-red-500">⚠</span>}
                        </span>
                    </div>
                    <HourBar logged={card.logged_hours} quoted={card.quoted_hours} />
                </div>
            )}

            {/* Sections */}
            {card.sections.length > 0 && (
                <div className="px-5 py-3 border-b border-gray-100">
                    <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">Sections</p>
                    <div className="grid grid-cols-1 gap-2">
                        {card.sections.map(s => (
                            <SectionPill
                                key={s.id}
                                section={{ ...s, job_card_id: card.id }}
                                activeClock={activeClock}
                                onClockOn={onClockOn}
                                onClockOff={onClockOff}
                                loading={loading}
                            />
                        ))}
                    </div>
                </div>
            )}

            {/* Footer */}
            <div className="px-5 py-4 mt-auto">
                <Link
                    href={`/hours?job_card_id=${card.id}`}
                    className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold
                        border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
                >
                    <PlusIcon className="w-4 h-4" />
                    Log Hours Manually
                </Link>
            </div>
        </div>
    );
}

// ── Filter bar ────────────────────────────────────────────────────────────────

const FILTERS = [
    { key: 'all',               label: 'All Jobs'         },
    { key: 'mine',              label: 'My Jobs'          },
    { key: 'open',              label: 'Open'             },
    { key: 'in_progress',       label: 'In Progress'      },
    { key: 'awaiting_approval', label: 'Awaiting Approval'},
    { key: 'approved',          label: 'Approved'         },
];

// ── Main ──────────────────────────────────────────────────────────────────────

export default function Board({ jobCards, currentUserId, activeClock: initialClock }) {
    const [filter, setFilter] = useState('all');
    const { activeClock, elapsed, loading, clockOn, clockOff } = useJobClock(initialClock);

    const filtered = (() => {
        if (filter === 'all')  return jobCards;
        if (filter === 'mine') return jobCards.filter(c => c.sections.some(s => s.is_mine));
        return jobCards.filter(c => c.status === filter);
    })();

    const myJobsCount = jobCards.filter(c => c.sections.some(s => s.is_mine)).length;

    return (
        <WorkshopLayout title="Board">
            {/* Bottom clock banner */}
            <ClockBanner
                activeClock={activeClock}
                elapsed={elapsed}
                loading={loading}
                onStop={clockOff}
                jobCards={jobCards}
            />

            <div className="max-w-7xl mx-auto px-4 sm:px-6 py-8" style={{ paddingBottom: activeClock ? '96px' : undefined }}>

                {/* Header */}
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900"
                            style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
                            Shop Floor Board
                        </h1>
                        <p className="text-sm text-gray-500 mt-1">
                            {jobCards.length} active job card{jobCards.length !== 1 ? 's' : ''}
                            {myJobsCount > 0 && (
                                <span className="ml-2 text-blue-700 font-medium">
                                    · {myJobsCount} assigned to you
                                </span>
                            )}
                        </p>
                    </div>
                    <Link
                        href="/hours"
                        className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
                    >
                        <ClockIcon className="w-4 h-4" />
                        My Hours
                    </Link>
                </div>

                {/* Filters */}
                <div className="flex gap-1 mb-6 border-b border-gray-200 overflow-x-auto">
                    {FILTERS.map(f => {
                        const count = f.key === 'all' ? jobCards.length
                            : f.key === 'mine' ? myJobsCount
                            : jobCards.filter(c => c.status === f.key).length;
                        return (
                            <button
                                key={f.key}
                                onClick={() => setFilter(f.key)}
                                className={`px-4 py-2.5 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
                                    filter === f.key
                                        ? 'border-gray-900 text-gray-900'
                                        : 'border-transparent text-gray-500 hover:text-gray-700'
                                }`}
                            >
                                {f.label}
                                {count > 0 && (
                                    <span className={`ml-1.5 text-xs px-1.5 py-0.5 rounded-full ${
                                        filter === f.key ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-500'
                                    }`}>
                                        {count}
                                    </span>
                                )}
                            </button>
                        );
                    })}
                </div>

                {/* Grid */}
                {filtered.length === 0 ? (
                    <div className="text-center py-16 text-gray-400">
                        <CarIcon className="w-10 h-10 mx-auto mb-3 opacity-30" />
                        <p className="text-base font-medium">No job cards in this view</p>
                    </div>
                ) : (
                    <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                        {filtered.map(card => (
                            <JobCardTile
                                key={card.id}
                                card={card}
                                activeClock={activeClock}
                                onClockOn={clockOn}
                                onClockOff={clockOff}
                                loading={loading}
                            />
                        ))}
                    </div>
                )}
            </div>
        </WorkshopLayout>
    );
}
