'use client';

import { useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { formatCurrency as formatCurrencyUtil } from '@/lib/currency-formatter';

type CashboxShiftBreakdownItem = {
  id: string;
  startedAt: string;
  endedAt?: string;
  openingCash: number;
  cashSalesAmount: number;
  expectedCashAtClose: number;
  countedCashAtClose?: number;
};

type CashboxShiftBreakdownDialogProps = {
  employeeName: string;
  currencySymbol: string;
  shifts: CashboxShiftBreakdownItem[];
  currentCashBalance: number;
};

function formatShiftDateTime(value?: string) {
  const raw = String(value || '').trim();
  if (!raw) return '-';
  const date = new Date(raw);
  if (Number.isNaN(date.getTime())) return '-';
  return date.toLocaleString('ar', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export default function CashboxShiftBreakdownDialog({ employeeName, currencySymbol, shifts, currentCashBalance }: CashboxShiftBreakdownDialogProps) {
  // فقط الورديات غير المرحلة (التي لم تُرحّل بعد)
  const untransferredShifts = useMemo(
    () => shifts.filter((shift) => !('transferred' in shift) || !shift.transferred),
    [shifts],
  );
  const totalShiftNet = useMemo(
    () => untransferredShifts.reduce((sum, shift) => sum + (Number(shift.expectedCashAtClose || 0) - Number(shift.openingCash || 0)), 0),
    [untransferredShifts],
  );
  const balanceDifference = useMemo(
    () => Number(currentCashBalance || 0) - Number(totalShiftNet || 0),
    [currentCashBalance, totalShiftNet],
  );
  const hasDifference = Math.abs(balanceDifference) > 0.009;

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button type="button" variant="ghost" size="sm" className="h-8 px-2">
          تفاصيل الورديات
        </Button>
      </DialogTrigger>
      <DialogContent className="max-h-[80vh] max-w-3xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{`تفاصيل الورديات - ${employeeName}`}</DialogTitle>
          <DialogDescription>قيمة كل وردية قبل الترحيل إلى الصندوق الرئيسي.</DialogDescription>
        </DialogHeader>

        {untransferredShifts.length === 0 ? (
          <div className="rounded-md border border-dashed px-3 py-6 text-center text-sm text-muted-foreground">
            لا توجد ورديات غير مرحلة إلى الصندوق الرئيسي.
          </div>
        ) : (
          <div className="space-y-2">
            <div className="grid grid-cols-7 gap-2 rounded-md border bg-muted/30 px-2 py-2 text-xs font-semibold">
              <div>بداية الوردية</div>
              <div>نهاية الوردية</div>
              <div className="text-right">افتتاحي</div>
              <div className="text-right">مبيعات نقدية</div>
              <div className="text-right">صافي الوردية</div>
              <div className="text-right">الجرد الفعلي</div>
              <div className="text-right">الفارق</div>
            </div>
            {untransferredShifts.map((shift) => {
              const netShift = Number(shift.expectedCashAtClose || 0) - Number(shift.openingCash || 0);
              const counted = typeof shift.countedCashAtClose === 'number' ? shift.countedCashAtClose : undefined;
              const variance =
                typeof counted === 'number'
                  ? counted - Number(shift.expectedCashAtClose || 0)
                  : undefined;
              return (
                <div key={shift.id} className="grid grid-cols-7 gap-2 rounded-md border px-2 py-2 text-sm">
                  <div className="text-xs text-muted-foreground">{formatShiftDateTime(shift.startedAt)}</div>
                  <div className="text-xs text-muted-foreground">{formatShiftDateTime(shift.endedAt)}</div>
                  <div className="text-right font-mono">{formatCurrencyUtil(shift.openingCash, currencySymbol)}</div>
                  <div className="text-right font-mono">{formatCurrencyUtil(shift.cashSalesAmount, currencySymbol)}</div>
                  <div className="text-right font-mono font-semibold">{formatCurrencyUtil(netShift, currencySymbol)}</div>
                  <div className="text-right font-mono">
                    {typeof counted === 'number' ? formatCurrencyUtil(counted, currencySymbol) : <span className="text-muted-foreground">-</span>}
                  </div>
                  <div className={
                    typeof variance === 'number'
                      ? `text-right font-mono font-semibold ${
                          Math.abs(variance) < 0.009
                            ? 'text-emerald-700'
                            : variance > 0
                              ? 'text-amber-700'
                              : 'text-destructive'
                        }`
                      : 'text-right font-mono text-muted-foreground'
                  }>
                    {typeof variance === 'number' ? formatCurrencyUtil(variance, currencySymbol) : '-'}
                  </div>
                </div>
              );
            })}
            <div className="mt-3 space-y-2 rounded-md border bg-primary/5 px-3 py-2">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">الرصيد الفعلي الحالي للصندوق</span>
                <span className="font-mono font-semibold">{formatCurrencyUtil(currentCashBalance, currencySymbol)}</span>
              </div>
              <div className="flex items-center justify-between border-t pt-2">
                <span className="text-sm font-medium">إجمالي صافي الورديات المعروضة</span>
                <span className="font-mono font-semibold">{formatCurrencyUtil(totalShiftNet, currencySymbol)}</span>
              </div>
              <div className="flex items-center justify-between border-t pt-2">
                <span className="text-sm font-medium">الفارق</span>
                <span
                  className={`font-mono font-semibold ${
                    !hasDifference
                      ? 'text-emerald-700'
                      : balanceDifference > 0
                        ? 'text-amber-700'
                        : 'text-destructive'
                  }`}
                >
                  {formatCurrencyUtil(balanceDifference, currencySymbol)}
                </span>
              </div>
              {hasDifference && (
                <p className="text-xs text-muted-foreground">
                  الفارق يعني أن الرصيد الفعلي للصندوق يتضمن حركات إضافية غير ظاهرة ضمن الورديات المعروضة.
                </p>
              )}
            </div>
          </div>
        )}

        <DialogFooter>
          <DialogClose asChild>
            <Button type="button" variant="outline">إغلاق</Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
