// @ts-nocheck
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  DollarSign,
  Clock,
  ShoppingCart,
  Wallet,
  LogOut,
  Plus,
  Trash2,
  ArrowUpCircle,
  ArrowDownCircle,
} from "lucide-react";
import PaymentBreakdownChart from "./PaymentBreakdownChart";
import SessionSalesTable from "./SessionSalesTable";
import type {
  CashRegisterSessionRecord,
  CashRegisterSellerRecord,
  CashMovementRecord,
  SessionSummary,
} from "@/types/modules/cashRegister";

interface Props {
  activeSession: CashRegisterSessionRecord;
  currentSeller: CashRegisterSellerRecord;
  summary: SessionSummary | undefined;
  movements: CashMovementRecord[];
  isLoadingSummary: boolean;
  onOpenCloseDialog: () => void;
  onOpenMovementDialog: () => void;
  onDeleteMovement: (id: string) => void;
}

export default function CashDashboard({
  activeSession,
  currentSeller,
  summary,
  movements,
  isLoadingSummary,
  onOpenCloseDialog,
  onOpenMovementDialog,
  onDeleteMovement,
}: Props) {
  const totalSales = summary?.total_sales ?? 0;
  const totalTransactions = summary?.total_transactions ?? 0;
  const expectedCash = summary?.expected_cash ?? 0;
  const movementsNet = (summary?.movements_income ?? 0) - (summary?.movements_expense ?? 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <h2 className="text-xl font-bold text-gray-900">Turno Activo</h2>
            <Badge className="bg-emerald-100 text-emerald-800">Abierta</Badge>
          </div>
          <p className="text-sm text-gray-500">
            {activeSession.session_number} &middot; {currentSeller.full_name} &middot;
            Abierto: {new Date(activeSession.opening_date!).toLocaleString("es-CL")}
          </p>
        </div>
        <Button
          onClick={onOpenCloseDialog}
          className="bg-gradient-to-r from-red-600 to-red-700"
        >
          <LogOut className="w-4 h-4 mr-2" />
          Cerrar Turno
        </Button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-5 pb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                <DollarSign className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Total Ventas</p>
                <p className="text-lg font-bold">${totalSales.toLocaleString("es-CL")}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-5 pb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-emerald-100 rounded-lg flex items-center justify-center">
                <ShoppingCart className="w-5 h-5 text-emerald-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Transacciones</p>
                <p className="text-lg font-bold">{totalTransactions}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-5 pb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center">
                <Wallet className="w-5 h-5 text-amber-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Efectivo Esperado</p>
                <p className="text-lg font-bold">${expectedCash.toLocaleString("es-CL")}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-5 pb-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                <Clock className="w-5 h-5 text-purple-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Apertura</p>
                <p className="text-lg font-bold">${Number(activeSession.opening_cash ?? 0).toLocaleString("es-CL")}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <PaymentBreakdownChart paymentBreakdown={summary?.payment_breakdown ?? []} />
        <SessionSalesTable summary={summary} isLoading={isLoadingSummary} />
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-3">
          <CardTitle className="text-base">Movimientos de Caja</CardTitle>
          <Button size="sm" variant="outline" onClick={onOpenMovementDialog}>
            <Plus className="w-4 h-4 mr-1" />
            Nuevo
          </Button>
        </CardHeader>
        <CardContent>
          {movements.length === 0 ? (
            <p className="text-center text-gray-500 py-4 text-sm">Sin movimientos registrados</p>
          ) : (
            <div className="space-y-2">
              {movements.map((m) => (
                <div
                  key={m.id}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div className="flex items-center gap-3">
                    {m.type === "income" ? (
                      <ArrowUpCircle className="w-5 h-5 text-emerald-600" />
                    ) : (
                      <ArrowDownCircle className="w-5 h-5 text-red-600" />
                    )}
                    <div>
                      <p className="text-sm font-medium">{m.description}</p>
                      <p className="text-xs text-gray-500">
                        {m.category === "deposit" && "Depósito"}
                        {m.category === "withdrawal" && "Retiro"}
                        {m.category === "petty_cash" && "Gasto menor"}
                        {m.category === "other" && "Otro"}
                        {m.created_at && ` · ${new Date(m.created_at).toLocaleTimeString("es-CL")}`}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span
                      className={`font-semibold text-sm ${m.type === "income" ? "text-emerald-600" : "text-red-600"}`}
                    >
                      {m.type === "income" ? "+" : "-"}${m.amount.toLocaleString("es-CL")}
                    </span>
                    <Button
                      size="sm"
                      variant="ghost"
                      className="h-7 w-7 p-0 text-gray-400 hover:text-red-600"
                      onClick={() => m.id && onDeleteMovement(String(m.id))}
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </Button>
                  </div>
                </div>
              ))}
              {(summary?.movements_income ?? 0) > 0 || (summary?.movements_expense ?? 0) > 0 ? (
                <div className="flex justify-between pt-2 border-t text-sm">
                  <span className="text-gray-600">Neto movimientos:</span>
                  <span className={`font-semibold ${movementsNet >= 0 ? "text-emerald-600" : "text-red-600"}`}>
                    {movementsNet >= 0 ? "+" : ""}${movementsNet.toLocaleString("es-CL")}
                  </span>
                </div>
              ) : null}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
