<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import { Clock, ArrowRightLeft, Coffee, MapPin, Laptop, FileText } from 'lucide-vue-next';
import employee from '@/routes/employee';
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';


const props = defineProps<{
    today: any;
}>();

const page = usePage();
const user = computed(() => page.props.auth.user);

// Status Logic
const status = computed(() => {
    if (!props.today?.clock_in || props.today?.clock_out) return 'OFFLINE';
    if (props.today?.break_start) return 'BREAK';
    return 'ACTIVE';
});

// Timer Logic
const elapsedTime = ref(0);
const breakTime = ref(0);
let timerInterval: any = null;
const serverTimeOffset = ref(0);

const calculateElapsedTime = () => {
    if (!props.today?.clock_in) {
        elapsedTime.value = 0;
        breakTime.value = 0;
        return;
    }

    // Use server-synchronized "now"
    const now = new Date().getTime() + serverTimeOffset.value;
    const clockInTime = new Date(props.today.clock_in).getTime();
    let totalSeconds = 0;

    if (props.today.clock_out) {
        // Shift ended
        const clockOutTime = new Date(props.today.clock_out).getTime();
        totalSeconds = Math.floor((clockOutTime - clockInTime) / 1000);
        breakTime.value = 0;
    } else if (props.today.break_start) {
        // Currently on break
        const breakStartTime = new Date(props.today.break_start).getTime();
        totalSeconds = Math.floor((breakStartTime - clockInTime) / 1000);
        
        // Calculate current break duration
        breakTime.value = Math.max(0, Math.floor((now - breakStartTime) / 1000));
    } else {
        // Currently working
        totalSeconds = Math.max(0, Math.floor((now - clockInTime) / 1000));
        breakTime.value = 0;
    }

    // Subtract accumulated previous breaks
    const totalBreakSec = Number(props.today.total_break_seconds || 0);
    totalSeconds -= totalBreakSec;

    elapsedTime.value = Math.max(0, totalSeconds);
    
    // Debug logging (throttled to avoid flooding)
    if (elapsedTime.value % 10 === 0) {
        console.log('[Timer Debug]', {
            status: status.value,
            now: new Date(now).toISOString(),
            clockIn: props.today.clock_in,
            totalBreakSec,
            calculatedElapsedTime: elapsedTime.value,
            calculatedBreakTime: breakTime.value
        });
    }
};

onMounted(() => {
    // Sync clock with server
    if (page.props.server_time) {
        const serverAt = new Date(page.props.server_time as string).getTime();
        const clientAt = new Date().getTime();
        serverTimeOffset.value = serverAt - clientAt;
    }

    // Immediate calculation
    calculateElapsedTime();
    // Update every second to keep sync
    timerInterval = setInterval(calculateElapsedTime, 1000);
});

onUnmounted(() => {
    if (timerInterval) clearInterval(timerInterval);
});

watch(() => props.today, () => {
    calculateElapsedTime();
}, { deep: true });

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

// Forms
const clockInForm = useForm({
    work_mode: 'office',
    note: '',
});

const form = useForm({});

// Modal State
const showClockOutModal = ref(false);


// Actions
const handleClockIn = () => {
    console.log('Clock In button clicked!');
    console.log('Form data:', { work_mode: clockInForm.work_mode, note: clockInForm.note });
    
    clockInForm.post(employee.attendance.clock_in.url(), {
        preserveScroll: true,
        onStart: () => console.log('Request started'),
        onSuccess: () => console.log('Clock in successful!'),
        onError: (errors) => console.error('Clock in errors:', errors),
        onFinish: () => console.log('Request finished'),
    });
};

const handleClockOut = () => {
    showClockOutModal.value = true;
};

const confirmClockOut = () => {
    showClockOutModal.value = false;
    form.post(employee.attendance.clock_out.url(), {
        preserveScroll: true,
        onStart: () => console.log('Clock out request started'),
        onSuccess: () => console.log('Clock out successful!'),
        onError: (errors) => console.error('Clock out errors:', errors),
        onFinish: () => console.log('Clock out request finished'),
    });
};


const toggleBreak = () => {
    console.log('Break button clicked! Current status:', status.value);
    
    if (status.value === 'BREAK') {
        console.log('Ending break...');
        form.post(employee.attendance.end_break.url(), {
            preserveScroll: true,
            onSuccess: () => console.log('Break ended successfully'),
            onError: (errors) => console.error('End break errors:', errors),
        });
    } else {
        console.log('Starting break...');
        form.post(employee.attendance.start_break.url(), {
            preserveScroll: true,
            onSuccess: () => console.log('Break started successfully'),
            onError: (errors) => console.error('Start break errors:', errors),
        });
    }
};

const shiftTime = computed(() => {
    const settings = (page.props.branding as any)?.business_settings;
    if (!settings?.shift_start_time || !settings?.shift_end_time) {
        return '09:00 AM — 06:00 PM';
    }
    
    const formatTime = (time: string) => {
        const [hours, minutes] = time.split(':');
        const date = new Date();
        date.setHours(parseInt(hours), parseInt(minutes));
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    };

    return `${formatTime(settings.shift_start_time)} — ${formatTime(settings.shift_end_time)}`;
});


</script>

<template>
    <div class="xl:col-span-3 p-5 rounded-xl border flex flex-col md:flex-row items-center gap-8 bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 shadow-sm transition-all duration-300">
        <div class="flex-1 w-full">
            <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-4">
                    <div>
                        <h2 class="text-lg font-bold text-slate-800 dark:text-slate-100">{{ __('shift_controls') }}</h2>
                        <p class="text-xs text-slate-500">{{ __('scheduled') }}: {{ shiftTime }} ({{ __('general_shift') }})</p>
                    </div>
                </div>
                <div class="px-3 py-1 rounded-md text-[10px] font-black tracking-widest uppercase border transition-colors"
                    :class="{
                        'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20': status === 'ACTIVE',
                        'bg-amber-50 text-amber-600 border-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20': status === 'BREAK',
                        'bg-slate-100 text-slate-500 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700': status === 'OFFLINE'
                    }"
                >
                    {{ __(status) }}
                </div>
            </div>

            <div class="flex flex-wrap gap-4">
                <!-- Main Action Button -->
                <button 
                    v-if="status === 'OFFLINE'"
                    @click="handleClockIn"
                    :disabled="clockInForm.processing"
                    class="flex-1 min-w-[160px] py-3 rounded-lg font-bold text-sm flex items-center justify-center gap-2 transition-all bg-[var(--brand-primary)] hover:opacity-90 text-white shadow-md hover:shadow-lg hover:-translate-y-0.5"
                >
                    <Clock :size="18"/> {{ __('clock_in') }}
                </button>

                <button 
                    v-else
                    @click="handleClockOut"
                    :disabled="form.processing"
                    class="flex-1 min-w-[160px] py-3 rounded-lg font-bold text-sm flex items-center justify-center gap-2 transition-all bg-rose-50 text-rose-600 border border-rose-100 hover:bg-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20 dark:hover:bg-rose-500/20"
                >
                    <ArrowRightLeft :size="18"/> {{ __('clock_out') }}
                </button>

                <!-- Break Button -->
                <button 
                    @click="toggleBreak"
                    :disabled="status === 'OFFLINE' || form.processing"
                    class="flex-1 min-w-[160px] py-3 rounded-lg font-bold text-sm flex items-center justify-center gap-2 border transition-all"
                    :class="{
                        'opacity-50 cursor-not-allowed bg-slate-50 text-slate-400 dark:bg-slate-800 dark:border-slate-700': status === 'OFFLINE',
                        'bg-amber-500 text-white border-amber-600 shadow-md hover:bg-amber-600': status === 'BREAK',
                        'bg-white hover:bg-slate-50 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-200 dark:border-slate-700 dark:hover:bg-slate-700': status === 'ACTIVE'
                    }"
                >
                    <Coffee :size="18"/> {{ status === 'BREAK' ? __('end_break') : __('take_break') }}
                </button>

                <!-- Timer Display -->
                <div class="flex-1 min-w-[160px] px-4 py-3 rounded-lg border flex flex-col justify-center bg-slate-50 dark:bg-slate-800/50 border-slate-200 dark:border-slate-700">
                    <span class="text-[10px] text-slate-500 font-bold uppercase tracking-tight">{{ __('active_timer') }}</span>
                    <span class="text-xl font-mono font-bold text-slate-800 dark:text-slate-100">{{ formatTime(elapsedTime) }}</span>
                </div>

                <!-- Break Timer Display (only shown when on break) -->
                <div v-if="status === 'BREAK'" class="flex-1 min-w-[160px] px-4 py-3 rounded-lg border flex flex-col justify-center bg-amber-50 dark:bg-amber-500/10 border-amber-200 dark:border-amber-500/20">
                    <span class="text-[10px] text-amber-600 dark:text-amber-400 font-bold uppercase tracking-tight">{{ __('break_timer') }}</span>
                    <span class="text-xl font-mono font-bold text-amber-700 dark:text-amber-300">{{ formatTime(breakTime) }}</span>
                </div>
            </div>
        </div>

        <div class="w-px h-16 bg-slate-200 dark:bg-slate-700 hidden md:block"></div>

        <!-- Work Settings -->
        <div class="w-full md:w-auto space-y-3">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg flex items-center justify-center transition-colors"
                    :class="clockInForm.work_mode === 'office' ? 'bg-blue-100 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400' : 'bg-purple-100 text-purple-600 dark:bg-purple-500/20 dark:text-purple-400'"
                >
                    <MapPin v-if="clockInForm.work_mode === 'office'" :size="16"/>
                    <Laptop v-else :size="16"/>
                </div>
                <div class="flex-1">
                    <p class="text-[10px] text-slate-500 font-bold uppercase">{{ __('work_mode') }}</p>
                    <select 
                        v-model="clockInForm.work_mode" 
                        :disabled="status !== 'OFFLINE'"
                        class="text-sm font-bold bg-transparent focus:outline-none cursor-pointer border-none p-0 pe-8 text-slate-700 dark:text-slate-200 focus:ring-0 disabled:opacity-50"
                    >
                        <option value="office">{{ __('in_office_hq') }}</option>
                        <option value="remote">{{ __('remote_home') }}</option>
                    </select>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400 flex items-center justify-center">
                    <FileText :size="16"/>
                </div>
                <div>
                    <p class="text-[10px] text-slate-500 font-bold uppercase">{{ __('daily_note') }}</p>
                    <input 
                        type="text" 
                        v-model="clockInForm.note"
                        :disabled="status !== 'OFFLINE'"
                        :placeholder="__('add_remark')" 
                        class="text-sm font-medium bg-transparent focus:outline-none w-32 border-b border-transparent focus:border-slate-300 dark:focus:border-slate-600 p-0 text-slate-700 dark:text-slate-200 placeholder-slate-400 disabled:opacity-50 focus:ring-0" 
                    />
                </div>
            </div>
        </div>

        <!-- Clock Out Confirmation Modal -->
        <ConfirmationModal 
            :show="showClockOutModal"
            :title="__('clock_out')"
            :message="__('are_you_sure_to_clock_out')"
            :confirm-text="__('clock_out')"
            type="warning"
            :processing="form.processing"
            @close="showClockOutModal = false"
            @confirm="confirmClockOut"
        />
    </div>
</template>
