import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Wallet, HandCoins, Coins } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtDate, fmtTime } from '../shared/reportDesignTokens'

function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }

export default function Payments() {
  const [waiterId, setWaiterId] = useState('all')
  const [mode, setMode] = useState('range')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [businessDayId, setBusinessDayId] = useState('all')

  const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').then(r => r.data), staleTime: 5 * 60 * 1000 })
  const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })

  const queryParams = {
    ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}),
    ...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
    ...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
  }

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['shifts-payments', waiterId, mode, from, to, businessDayId],
    queryFn: () => client.get('/api/reports/shifts', { params: queryParams }).then(r => r.data),
    staleTime: 60 * 1000,
  })

  const waiterOptions = [{ value: 'all', label: 'Όλοι οι Σερβιτόροι' }, ...((waitersData?.waiters || []).map(w => ({ value: String(w.id), label: w.name })))]
  const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]

  const shifts = data?.shifts || []
  const totals = shifts.reduce((acc, s) => {
    acc.starting += s.starting_cash || 0
    acc.collected += s.total_collected || 0
    acc.owed += s.net_to_deliver || 0
    return acc
  }, { starting: 0, collected: 0, owed: 0 })

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={5} /></div>
  if (isError) return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
      <div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50">Επανάληψη</button></div>
    </div>
  )

  return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar right={
        <ExportButton
          endpoint="/api/reports/shifts/export"
          params={queryParams}
          filename={`shift-payments-${from}-to-${to}.csv`}
        />
      }>
        <FilterSelect value={waiterId} onChange={setWaiterId} options={waiterOptions} label="Σερβιτόρος" />
        <WorkDayDateToggle mode={mode} onChange={setMode} />
        {mode === 'workday' ? (
          <FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
        ) : (
          <>
            <FilterDateInput value={from} onChange={setFrom} label="Από" />
            <FilterDateInput value={to} onChange={setTo} label="Έως" />
          </>
        )}
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <div className="mb-4 grid grid-cols-3 gap-4">
          <StatCard label="Αρχικά Μετρητά" value={fmtEUR(totals.starting)} sub={`σε ${shifts.length} βάρδιες`} icon={Wallet} />
          <StatCard label="Συνολικές Εισπράξεις" value={fmtEUR(totals.collected)} sub="από πληρωμένες παραγγελίες" icon={HandCoins} />
          <StatCard label="Οφείλεται στον Διαχειριστή" value={fmtEUR(totals.owed)} sub="προς εκκαθάριση" icon={Coins} accent />
        </div>

        <Panel title="Εκκαθάριση ανά Βάρδια" padded={false}>
          {shifts.length === 0 ? (
            <EmptyState title="Δεν υπάρχει τίποτα" description="Δεν υπάρχουν βάρδιες στην επιλεγμένη περίοδο." />
          ) : (
            <DataTable>
              <THead>
                <TH>Σερβιτόρος</TH>
                <TH>Βάρδια</TH>
                <TH align="right">Αρχικά Μετρητά</TH>
                <TH align="right">Εισπράχθηκαν</TH>
                <TH align="right">Σύνολο στην Τσέπη</TH>
                <TH>Κατάσταση</TH>
              </THead>
              <tbody>
                {shifts.map(s => (
                  <TR key={s.id} highlight={s.is_active} striped>
                    <TD><WaiterAvatar name={s.waiter_name} id={s.waiter_id} /></TD>
                    <TD mono className="text-slate-500">
                      {fmtDate(s.started_at)} · {fmtTime(s.started_at)}–{s.ended_at ? fmtTime(s.ended_at) : 'now'}
                    </TD>
                    <TD mono align="right">{fmtEUR(s.starting_cash)}</TD>
                    <TD mono align="right">{fmtEUR(s.total_collected)}</TD>
                    <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(s.net_to_deliver)}</TD>
                    <TD><StatusBadge status={s.is_active ? 'active' : 'closed'} pulse /></TD>
                  </TR>
                ))}
                <tr className="bg-slate-50">
                  <TD colSpan={2} className="py-3 text-[11px] font-semibold uppercase tracking-wider text-slate-500">Σύνολα</TD>
                  <TD mono align="right" className="py-3 font-semibold text-slate-900">{fmtEUR(totals.starting)}</TD>
                  <TD mono align="right" className="py-3 font-semibold text-slate-900">{fmtEUR(totals.collected)}</TD>
                  <TD mono align="right" className="py-3 text-base font-semibold text-sky-700">{fmtEUR(totals.owed)}</TD>
                  <TD />
                </tr>
              </tbody>
            </DataTable>
          )}
        </Panel>
      </div>
    </div>
  )
}
