// Chấm công của tôi — Phase 10.4 G-P1 (S38 2026-05-28).
// SKELETON: web GPS check-in/out + tháng calendar view.
// File MIRROR SHA256 identical fe-user counterpart.
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Clock, LogIn, LogOut, MapPin } from 'lucide-react'
import { toast } from 'sonner'
import { PageHeader } from '@/components/PageHeader'
import { Button } from '@/components/ui/Button'
import { api } from '@/lib/api'
import { getErrorMessage } from '@/lib/apiError'
import { cn } from '@/lib/cn'
import type { AttendanceDto } from '@/types/workflowApps'

function formatTime(iso: string | null): string {
  if (!iso) return '—'
  return new Date(iso).toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })
}

export function MyAttendancePage() {
  const qc = useQueryClient()
  const now = new Date()
  const [year, setYear] = useState(now.getFullYear())
  const [month, setMonth] = useState(now.getMonth() + 1)
  const [gpsStatus, setGpsStatus] = useState<string>('Chưa lấy vị trí')

  const list = useQuery({
    queryKey: ['attendances-me', { year, month }],
    queryFn: async () => (await api.get<AttendanceDto[]>('/attendances/me', { params: { year, month } })).data,
  })

  const today = list.data?.find((a) => a.attendanceDate.startsWith(now.toISOString().slice(0, 10)))

  const getGps = (): Promise<{ lat: number; long: number; accuracy: number } | null> =>
    new Promise((resolve) => {
      if (!navigator.geolocation) {
        setGpsStatus('Trình duyệt không hỗ trợ GPS')
        resolve(null)
        return
      }
      setGpsStatus('Đang lấy vị trí...')
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          setGpsStatus(`✓ Đã lấy vị trí (sai số ${pos.coords.accuracy.toFixed(0)}m)`)
          resolve({ lat: pos.coords.latitude, long: pos.coords.longitude, accuracy: pos.coords.accuracy })
        },
        (err) => {
          setGpsStatus(`✗ Lỗi GPS: ${err.message}`)
          resolve(null)
        },
        { enableHighAccuracy: true, timeout: 10000 },
      )
    })

  const checkIn = useMutation({
    mutationFn: async () => {
      const gps = await getGps()
      await api.post('/attendances/check-in', {
        latitude: gps?.lat ?? null,
        longitude: gps?.long ?? null,
        accuracy: gps?.accuracy ?? null,
        note: null,
      })
    },
    onSuccess: () => {
      toast.success('Đã check-in')
      qc.invalidateQueries({ queryKey: ['attendances-me'] })
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const checkOut = useMutation({
    mutationFn: async () => {
      const gps = await getGps()
      await api.post('/attendances/check-out', {
        latitude: gps?.lat ?? null,
        longitude: gps?.long ?? null,
        accuracy: gps?.accuracy ?? null,
      })
    },
    onSuccess: () => {
      toast.success('Đã check-out')
      qc.invalidateQueries({ queryKey: ['attendances-me'] })
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  return (
    <div className="space-y-4">
      <PageHeader title="Chấm công" description="Web GPS check-in/out + lịch sử tháng" />

      <div className="rounded-lg border bg-card p-4 space-y-3">
        <div className="flex items-center justify-between">
          <div>
            <div className="text-sm font-medium">Hôm nay {now.toLocaleDateString('vi-VN')}</div>
            <div className="text-xs text-muted-foreground mt-1 flex items-center gap-1">
              <MapPin className="h-3 w-3" /> {gpsStatus}
            </div>
          </div>
          <div className="flex gap-2">
            <Button
              onClick={() => checkIn.mutate()}
              disabled={checkIn.isPending || !!today?.checkInAt}
              className="bg-emerald-600 hover:bg-emerald-700"
            >
              <LogIn className="mr-2 h-4 w-4" />
              {today?.checkInAt ? `Vào: ${formatTime(today.checkInAt)}` : 'Check-in'}
            </Button>
            <Button
              onClick={() => checkOut.mutate()}
              disabled={checkOut.isPending || !today?.checkInAt || !!today?.checkOutAt}
              className="bg-orange-600 hover:bg-orange-700"
            >
              <LogOut className="mr-2 h-4 w-4" />
              {today?.checkOutAt ? `Ra: ${formatTime(today.checkOutAt)}` : 'Check-out'}
            </Button>
          </div>
        </div>
      </div>

      <div className="rounded-lg border bg-card p-4">
        <div className="flex items-center gap-3 mb-3">
          <select value={month} onChange={(e) => setMonth(Number(e.target.value))} className="rounded-md border px-2 py-1 text-sm">
            {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
              <option key={m} value={m}>Tháng {m}</option>
            ))}
          </select>
          <select value={year} onChange={(e) => setYear(Number(e.target.value))} className="rounded-md border px-2 py-1 text-sm">
            {[2025, 2026, 2027].map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </div>

        <table className="w-full text-sm">
          <thead className="border-b bg-muted/50">
            <tr>
              <th className="px-3 py-2 text-left">Ngày</th>
              <th className="px-3 py-2 text-left">Vào</th>
              <th className="px-3 py-2 text-left">Ra</th>
              <th className="px-3 py-2 text-right">Giờ làm</th>
              <th className="px-3 py-2 text-left">Ghi chú</th>
            </tr>
          </thead>
          <tbody>
            {list.isLoading && (
              <tr><td colSpan={5} className="px-3 py-6 text-center text-muted-foreground">Đang tải...</td></tr>
            )}
            {!list.isLoading && (list.data?.length ?? 0) === 0 && (
              <tr><td colSpan={5} className="px-3 py-6 text-center text-muted-foreground">
                <Clock className="mx-auto h-8 w-8 mb-2 opacity-50" />
                Chưa có dữ liệu chấm công tháng này.
              </td></tr>
            )}
            {list.data?.map((a) => (
              <tr key={a.id} className={cn('border-b', !a.checkOutAt && 'bg-amber-50/30')}>
                <td className="px-3 py-2">{new Date(a.attendanceDate).toLocaleDateString('vi-VN')}</td>
                <td className="px-3 py-2 tabular-nums">{formatTime(a.checkInAt)}</td>
                <td className="px-3 py-2 tabular-nums">{formatTime(a.checkOutAt)}</td>
                <td className="px-3 py-2 text-right tabular-nums">{a.workHours?.toFixed(2) ?? '—'}</td>
                <td className="px-3 py-2 text-xs text-muted-foreground">{a.note ?? '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
