import { useEffect, useState } from 'react';
import { Clock, LogIn, LogOut } from 'lucide-react';
import api from '../lib/api';
import { PageHeader } from '../components/ui/LinearPrimitives';

export default function TimeclockPage() {
    const [logs, setLogs] = useState<any[]>([]);
    const [status, setStatus] = useState<'CLOCKED_OUT' | 'CLOCKED_IN'>('CLOCKED_OUT');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchLogs();
    }, []);

    const fetchLogs = async () => {
        setLoading(true);
        try {
            const { data } = await api.get('/timeclock/logs');
            setLogs(data);
            const active = data.find((l: any) => !l.endTime);
            setStatus(active ? 'CLOCKED_IN' : 'CLOCKED_OUT');
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    const handleClock = async (action: 'in' | 'out') => {
        try {
            if (action === 'in') {
                await api.post('/timeclock/clock-in', { activityType: 'General' });
            } else {
                await api.post('/timeclock/clock-out', {});
            }
            await fetchLogs();
        } catch (e: any) {
            alert(e.response?.data?.message || 'Error clocking');
        }
    };

    return (
        <div className="max-w-2xl mx-auto space-y-6 animate-in">
            <PageHeader
                title="Time Clock"
                subtitle={new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
            />

            {/* Status Card */}
            <div className="card p-8 text-center">
                <div className="mb-6">
                    <span className="text-xs font-medium text-tertiary uppercase tracking-wider">
                        Current Status
                    </span>
                    <div className={`
                        text-xl font-semibold mt-2
                        ${status === 'CLOCKED_IN' ? 'text-success' : 'text-secondary'}
                    `}>
                        {status === 'CLOCKED_IN' ? 'Clocked In' : 'Clocked Out'}
                    </div>
                </div>

                <div className="flex gap-4 justify-center">
                    <button
                        onClick={() => handleClock('in')}
                        disabled={status === 'CLOCKED_IN'}
                        className={`
                            w-32 h-32 rounded-full font-semibold text-sm flex flex-col items-center justify-center gap-2
                            transition-all duration-normal
                            disabled:opacity-40 disabled:cursor-not-allowed
                            ${status !== 'CLOCKED_IN'
                                ? 'bg-success text-white hover:scale-105 shadow-lg'
                                : 'bg-tertiary text-tertiary'
                            }
                        `}
                    >
                        <LogIn size={24} />
                        Clock In
                    </button>
                    <button
                        onClick={() => handleClock('out')}
                        disabled={status === 'CLOCKED_OUT'}
                        className={`
                            w-32 h-32 rounded-full font-semibold text-sm flex flex-col items-center justify-center gap-2
                            transition-all duration-normal
                            disabled:opacity-40 disabled:cursor-not-allowed
                            ${status === 'CLOCKED_IN'
                                ? 'bg-destructive text-white hover:scale-105 shadow-lg'
                                : 'bg-tertiary text-tertiary'
                            }
                        `}
                    >
                        <LogOut size={24} />
                        Clock Out
                    </button>
                </div>
            </div>

            {/* Logs Table */}
            <div className="card overflow-hidden">
                <div className="p-4 border-b border-subtle flex items-center gap-2">
                    <Clock size={16} className="text-tertiary" />
                    <h3 className="text-sm font-medium text-primary">Recent Logs</h3>
                </div>

                {loading ? (
                    <div className="p-8 text-center">
                        <div className="skeleton w-8 h-8 rounded-full mx-auto" />
                    </div>
                ) : logs.length === 0 ? (
                    <div className="p-8 text-center text-tertiary text-sm">
                        No time logs yet
                    </div>
                ) : (
                    <div className="divide-y divide-subtle">
                        {logs.slice(0, 10).map(log => (
                            <div key={log.id} className="flex items-center justify-between p-4 hover:bg-tertiary transition-colors duration-fast">
                                <div>
                                    <div className="text-sm text-primary font-medium">
                                        {new Date(log.startTime).toLocaleDateString()}
                                    </div>
                                    <div className="text-xs text-tertiary">
                                        {log.activityType}
                                    </div>
                                </div>
                                <div className="text-right">
                                    <div className="text-sm text-primary">
                                        {new Date(log.startTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                        {' → '}
                                        {log.endTime
                                            ? new Date(log.endTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                                            : <span className="text-success">Active</span>
                                        }
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
