"use client";

import { useTransition, useState, useEffect } from "react";
import { format } from "date-fns";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { handleRejectLeaveRequest } from "@/lib/actions";
import { type LeaveRequest } from "@/lib/types";
import { Check, Loader2, X, DollarSign } from "lucide-react";
import { ApproveAdvanceDialog } from "./approve-advance-dialog";

type AdvanceRequestsTranslation = {
  employee: string;
  requestDetails: string;
  reason: string;
  status: string;
  noRequests: string;
  approve: string;
  reject: string;
  advanceDetails: string;
  approveDialogTitle: string;
  approveDialogDescription: string;
  installmentsCountLabel: string;
  repaymentStartLabel: string;
  month: string;
  year: string;
  repaymentPreviewTitle: string;
  repaymentPreviewDescription: string;
  confirmApproval: string;
  monthlyRepaymentLabel: string;
  repaymentPreviewMonthlyPayment: string;
  repaymentPreviewNumPayments: string;
  repaymentPreviewStartDate: string;
}

type GlobalTranslation = {
    cancel: string;
}

export default function AdvanceRequestsTable({ requests, t, tGlobal }: { requests: LeaveRequest[], t: AdvanceRequestsTranslation, tGlobal: GlobalTranslation }) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [isClient, setIsClient] = useState(false);
  const [dialogRequest, setDialogRequest] = useState<LeaveRequest | null>(null);

  useEffect(() => {
    setIsClient(true);
  }, []);
  
  const handleOpenApproveDialog = (request: LeaveRequest) => {
    setDialogRequest(request);
  };

  const handleCloseApproveDialog = () => {
    setDialogRequest(null);
  };

  const handleRejectAction = (employeeId: string, requestId: string) => {
    startTransition(async () => {
      const result = await handleRejectLeaveRequest(employeeId, requestId);
      if (result.success) {
        toast({
          title: 'تم',
          description: result.message,
        });
      } else {
        toast({
          title: 'خطأ',
          description: result.error,
          variant: 'destructive',
        });
      }
    });
  };
  
  const renderRequestDetails = (request: LeaveRequest) => {
    if (!isClient) {
        return <span className="text-muted-foreground italic">Loading...</span>;
    }
    return (
        <div className="flex flex-col">
           <div className="flex items-center gap-2">
             <DollarSign className="h-4 w-4 text-muted-foreground"/>
             <span>{t.advanceDetails.replace('{amount}', request.amount?.toFixed(2) || '0')}</span>
           </div>
            {request.from && <span className="text-xs text-muted-foreground">{format(request.from, "MMM d, yyyy")}</span>}
       </div>
   );
  }

  return (
    <>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="text-start">{t.employee}</TableHead>
            <TableHead className="text-start">{t.requestDetails}</TableHead>
            <TableHead className="text-start">{t.reason}</TableHead>
            <TableHead className="text-start">{t.status}</TableHead>
            <TableHead className="text-end">Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {requests.length === 0 && (
              <TableRow>
                  <TableCell colSpan={5} className="text-center h-24 text-muted-foreground">
                      {t.noRequests}
                  </TableCell>
              </TableRow>
          )}
          {requests.map((request) => (
            <TableRow key={request.id}>
              <TableCell className="font-medium text-start">{request.employeeName}</TableCell>
              <TableCell className="text-start">
                {renderRequestDetails(request)}
              </TableCell>
              <TableCell className="text-start">{request.reason}</TableCell>
              <TableCell className="text-start">
                <Badge
                  variant={
                    request.status === "approved"
                      ? "default"
                      : request.status === "rejected"
                      ? "destructive"
                      : "secondary"
                  }
                  className={request.status === 'approved' ? 'bg-green-600' : ''}
                >
                  {request.status}
                </Badge>
              </TableCell>
              <TableCell className="text-end">
                {request.status === "pending" && (
                  <div className="flex gap-2 justify-end">
                      <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleOpenApproveDialog(request)}
                          disabled={isPending}
                          className="text-green-600 border-green-600 hover:bg-green-50 hover:text-green-700"
                      >
                          {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <Check className="me-2 h-4 w-4" />}
                          {t.approve}
                      </Button>
                      <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleRejectAction(request.employeeId, request.id)}
                          disabled={isPending}
                          className="text-red-600 border-red-600 hover:bg-red-50 hover:text-red-700"
                      >
                          {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <X className="me-2 h-4 w-4" />}
                          {t.reject}
                      </Button>
                  </div>
                )}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {dialogRequest && (
        <ApproveAdvanceDialog 
          request={dialogRequest}
          onClose={handleCloseApproveDialog}
          t={t}
          tGlobal={tGlobal}
        />
      )}
    </>
  );
}
