'use client';
import { useState } from 'react';
import { useSelectedStoreId } from '@/lib/stores/store-context';
import { timekeepingError, useClock, useClockCommand } from '@/hooks/use-timekeeping';
import { useScheduleSettings } from '@/lib/queries/use-scheduling';

export function ClockClient() {
  const store = useSelectedStoreId();
  return store ? <StoreClock key={store} store={store} /> : <p>Select a store to clock in.</p>;
}
function StoreClock({ store }: { store: string }) {
  const settings = useScheduleSettings(store);
  const timezone = settings.data?.data.timezone;
  const query = useClock(store);
  const command = useClockCommand(store, () => query.refetch());
  const [breakType, setBreakType] = useState<'paid' | 'unpaid'>('unpaid');
  const clock = query.data?.data;
  return <section className="mx-auto max-w-2xl space-y-6 p-4">
    <h1 className="text-2xl font-semibold">Clock</h1>
    {query.isPending && <p role="status">Loading clock…</p>}
    {query.error && <p role="alert">{timekeepingError(query.error)}</p>}
    {settings.error && <p role="alert">Store timezone unavailable. Punch timestamps are shown in UTC.</p>}
    {command.error != null && <p role="alert">{timekeepingError(command.error)}</p>}
    {clock && <>
      <p className="text-xl" aria-live="polite">{clock.status.replaceAll('_', ' ')}</p>
      <p className="text-sm">Server time: {new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short', timeZone: timezone ?? 'UTC' }).format(new Date(clock.server_time))} · {timezone ?? 'UTC'}</p>
      <div className="grid gap-4 sm:grid-cols-2">
        <button className="min-h-24 rounded-xl bg-primary p-6 text-xl font-semibold text-primary-foreground disabled:opacity-50" disabled={command.busy || command.retryable || !clock.allowed_actions.includes('clock')} onClick={() => command.run({ action: 'clock', state_revision: clock.state_revision })}>{clock.status === 'clocked_out' ? 'Clock in' : 'Clock out'}</button>
        <button className="min-h-24 rounded-xl border p-6 text-xl font-semibold disabled:opacity-50" disabled={command.busy || command.retryable || !clock.allowed_actions.includes('break')} onClick={() => command.run(clock.status === 'on_break' ? { action: 'break', state_revision: clock.state_revision } : { action: 'break', state_revision: clock.state_revision, break_type: breakType })}>{clock.status === 'on_break' ? 'End break' : 'Start break'}</button>
      </div>
      {clock.status === 'clocked_in' && <label className="block">Break type <select className="ml-2 rounded border p-3" value={breakType} disabled={command.busy || command.retryable} onChange={e => setBreakType(e.target.value as 'paid' | 'unpaid')}><option value="unpaid">Unpaid</option><option value="paid">Paid</option></select></label>}
      <h2 className="font-semibold">Recent punches</h2>
      {clock.punches.length === 0 ? <p>No punches yet.</p> : <ul className="divide-y">{clock.punches.map(p => <li className="py-3" key={p.id}>{p.punch_type.replaceAll('_', ' ')} — {new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short', timeZone: timezone ?? 'UTC' }).format(new Date(p.punched_at))}{p.break_type && ` (${p.break_type})`}</li>)}</ul>}
    </>}
    {command.retryable && <button className="rounded border p-3" disabled={command.busy} onClick={() => command.run()}>Retry same action</button>}
    <button className="rounded border p-3" disabled={query.isFetching || command.busy} onClick={() => query.refetch()}>Refresh status</button>
  </section>;
}
