import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { UserRoundX, ChevronRight, ExternalLink, Trash2, Eye } from 'lucide-react'
import toast from 'react-hot-toast'
import ShiftDetailModal from '../shared/ShiftDetailModal'
import DeleteConfirmModal from '../../../ui/DeleteConfirmModal'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LabelList } from 'recharts'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } 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, fmtDateTime, fmtDuration, fmtDate, fmtTime, fmtDateStr } 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 ShiftsOverview({ onNavigate } = {}) {
  const [waiterId, setWaiterId] = useState('all')
  const [from, setFrom] = useState(monthAgo())
  const [to, setTo] = useState(today())
  const [expanded, setExpanded] = useState(null)
  const [detailShift, setDetailShift] = useState(null) // { id, waiter_id }
  const [deleteShift, setDeleteShift] = useState(null) // shift object to delete

  const qc = useQueryClient()

  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 bdById = Object.fromEntries((bdData?.business_days || []).map(bd => [String(bd.id), bd]))

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['shifts', waiterId, from, to],
    queryFn: () => client.get('/api/reports/shifts', {
      params: {
        ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}),
        from: from + 'T00:00:00',
        to: to + 'T23:59:59',
      },
    }).then(r => r.data),
    staleTime: 0,
  })

  const deleteShiftMutation = useMutation({
    mutationFn: (id) => client.delete(`/api/shifts/${id}`),
    onSuccess: () => {
      toast.success('Η βάρδια διαγράφηκε')
      qc.invalidateQueries({ queryKey: ['shifts'] })
      qc.invalidateQueries({ queryKey: ['business-days-list'] })
      setDeleteShift(null)
    },
    onError: (err) => {
      toast.error(err?.response?.data?.detail || 'Σφάλμα διαγραφής βάρδιας')
      setDeleteShift(null)
    },
  })

  const waiterOptions = [
    { value: 'all', label: 'Όλοι οι Σερβιτόροι' },
    ...((waitersData?.waiters || []).map(w => ({ value: String(w.id), label: w.name }))),
  ]

  const shifts = data?.shifts || []

  if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} columns={8} /></div>
  if (isError) return (
    <div className="flex flex-col flex-1 min-h-0">
      <FilterBar right={null}><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={{ ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}), from: from + 'T00:00:00', to: to + 'T23:59:59' }}
          filename={`shifts-${from}-to-${to}.csv`}
        />
      }>
        <FilterSelect value={waiterId} onChange={setWaiterId} options={waiterOptions} label="Σερβιτόρος" />
        <FilterDateInput value={from} onChange={setFrom} label="Από" />
        <FilterDateInput value={to} onChange={setTo} label="Έως" />
      </FilterBar>

      <div className="flex-1 overflow-y-auto p-6">
        <Panel
          title="Όλες οι Βάρδιες"
          subtitle={`${shifts.length} βάρδιες · ${fmtDateStr(from)} → ${fmtDateStr(to)}`}
          padded={false}
        >
          {shifts.length === 0 ? (
            <EmptyState
              icon={UserRoundX}
              title="Δεν βρέθηκαν βάρδιες"
              description="Δοκιμάστε να αλλάξετε το εύρος ημερομηνιών ή τον σερβιτόρο."
            />
          ) : (
            <DataTable>
              <THead>
                <TH>Σερβιτόρος</TH>
                <TH>Έναρξη</TH>
                <TH>Λήξη</TH>
                <TH align="right">Διάρκεια</TH>
                <TH align="right">Αμοιβή/ώρα</TH>
                <TH align="right">Αποδοχές</TH>
                <TH align="right">Αρχικά Μετρητά</TH>
                <TH align="right">Εισπράχθηκαν</TH>
                <TH align="right">Οφείλει</TH>
                <TH align="right">Ταμείο</TH>
                <TH align="right">Ακυρώσεις</TH>
                <TH align="right">Αξία Ακυρ.</TH>
                <TH>Κατάσταση</TH>
                <TH className="w-28" />
              </THead>
              <tbody>
                {shifts.map(s => {
                  const isOpen = expanded === s.id
                  return [
                    <TR
                      key={`${s.id}-row`}
                      onClick={() => setExpanded(isOpen ? null : s.id)}
                      highlight={isOpen}
                      striped
                    >
                      <TD><WaiterAvatar name={s.waiter_name} id={s.waiter_id} /></TD>
                      <TD mono>{fmtDateTime(s.started_at)}</TD>
                      <TD mono>
                        {s.ended_at
                          ? fmtDateTime(s.ended_at)
                          : <span className="text-sky-600 font-medium">— ενεργή —</span>}
                      </TD>
                      <TD mono align="right">{fmtDuration(s.started_at, s.ended_at)}</TD>
                      <TD mono align="right">
                        {s.hourly_rate_snapshot != null
                          ? fmtEUR(s.hourly_rate_snapshot)
                          : <span className="text-slate-400 text-[11px]">—</span>}
                      </TD>
                      <TD mono align="right">
                        {s.shift_pay != null
                          ? <span className="font-semibold text-emerald-700">{fmtEUR(s.shift_pay)}</span>
                          : <span className="text-slate-400 text-[11px]">Δεν παρακολουθείται</span>}
                      </TD>
                      <TD mono align="right">{fmtEUR(s.starting_cash)}</TD>
                      <TD mono align="right">
                        <span className="font-semibold text-emerald-700">{fmtEUR(s.cash_sales ?? s.total_collected)}</span>
                        {(s.card_sales ?? 0) > 0 && (
                          <span className="block text-[10px] text-slate-400">+{fmtEUR(s.card_sales)} κάρτα</span>
                        )}
                      </TD>
                      <TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(s.net_to_deliver)}</TD>
                      <TD mono align="right">
                        {s.counted_cash_end != null ? (() => {
                          const d = s.cash_discrepancy
                          const isClean = d == null || Math.abs(d) < 0.005
                          const isSurplus = d != null && d > 0.005
                          const colorClass = isClean ? 'text-emerald-600 font-semibold'
                            : isSurplus ? 'text-emerald-600 font-semibold'
                            : 'text-red-600 font-semibold'
                          return (
                            <span className={colorClass}>
                              {fmtEUR(s.counted_cash_end)}
                              {d != null && Math.abs(d) >= 0.005 && (
                                <span className="block text-[10px] font-medium">
                                  {isSurplus ? `+${fmtEUR(d)}` : `−${fmtEUR(Math.abs(d))}`}
                                </span>
                              )}
                            </span>
                          )
                        })() : (
                          <span className="text-slate-400 text-[11px]">—</span>
                        )}
                      </TD>
                      <TD mono align="right">
                        {s.cancellations > 0
                          ? <span className="text-red-600 font-semibold">{s.cancellations}</span>
                          : <span className="text-slate-300">—</span>}
                      </TD>
                      <TD mono align="right">
                        {s.cancellation_value > 0
                          ? <span className="text-red-500">{fmtEUR(s.cancellation_value)}</span>
                          : <span className="text-slate-300">—</span>}
                      </TD>
                      <TD><StatusBadge status={s.is_active ? 'active' : 'closed'} pulse /></TD>
                      <TD align="right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={e => { e.stopPropagation(); setDetailShift({ id: s.id, waiter_id: s.waiter_id }) }}
                            className="rounded border border-sky-200 bg-white p-0.5 text-sky-400 hover:bg-sky-50 hover:text-sky-600"
                            title="Λεπτομέρειες βάρδιας"
                          >
                            <Eye size={13} />
                          </button>
                          {!s.is_active && (
                            <button
                              onClick={e => { e.stopPropagation(); setDeleteShift(s) }}
                              className="rounded border border-red-200 bg-white p-0.5 text-red-400 hover:bg-red-50 hover:text-red-600"
                              title="Διαγραφή βάρδιας"
                            >
                              <Trash2 size={13} />
                            </button>
                          )}
                          <ChevronRight className={`h-4 w-4 text-slate-400 transition-transform ${isOpen ? 'rotate-90' : ''}`} />
                        </div>
                      </TD>
                    </TR>,
                    isOpen && (
                      <tr key={`${s.id}-detail`}>
                        <td colSpan={14} className="border-b border-slate-100 bg-slate-50/60 px-6 py-3">
                          <div className="flex items-center gap-4 text-[12px] text-slate-500">
                            <span>
                              {'Εργάσιμη Μέρα: '}
                              {s.business_day_id ? (() => {
                                const bd = bdById[String(s.business_day_id)]
                                const label = bd
                                  ? `#${s.business_day_id} · ${fmtDate(bd.opened_at)} ${fmtTime(bd.opened_at)}`
                                  : `#${s.business_day_id}`
                                return onNavigate ? (
                                  <button
                                    onClick={e => { e.stopPropagation(); onNavigate({ parent: 'restaurant', sub: 'orders', initialBusinessDayId: s.business_day_id }) }}
                                    className="inline-flex items-center gap-1 text-sky-600 hover:text-sky-700 hover:underline font-medium"
                                  >
                                    {label}
                                    <ExternalLink className="h-3 w-3" />
                                  </button>
                                ) : <span>{label}</span>
                              })() : '—'}
                            </span>
                            <span>Σημειώσεις: {s.notes || '—'}</span>
                          </div>
                        </td>
                      </tr>
                    ),
                  ]
                })}
              </tbody>
            </DataTable>
          )}
        </Panel>
      </div>

      {detailShift && (
        <ShiftDetailModal
          shiftId={detailShift.id}
          shiftWaiterId={detailShift.waiter_id}
          onClose={() => setDetailShift(null)}
        />
      )}

      {deleteShift && (
        <DeleteConfirmModal
          title={`Διαγραφή Βάρδιας #${deleteShift.id}`}
          description={`Η βάρδια του ${deleteShift.waiter_name} (${fmtDateTime(deleteShift.started_at)} – ${fmtDateTime(deleteShift.ended_at)}) θα διαγραφεί μόνιμα.`}
          onConfirm={() => deleteShiftMutation.mutate(deleteShift.id)}
          onCancel={() => setDeleteShift(null)}
        />
      )}
    </div>
  )
}
