
"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 { handleApproveLeaveRequest, handleRejectLeaveRequest } from "@/lib/actions";
import { type LeaveRequest } from "@/lib/types";
import { Check, Loader2, X, DollarSign, Repeat } from "lucide-react";

type Translation = {
  employee: string;
  requestDetails: string;
  reason: string;
  status: string;
  noRequests: string;
  approve: string;
  reject: string;
  awaitingEmployeeApproval: string;
  advanceDetails: string;
  swapDetails: string;
}

export default function LeaveRequestsTable({ requests, t }: { requests: LeaveRequest[], t: Translation }) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const handleAction = (
    action: "approve" | "reject",
    employeeId: string,
    requestId: string
  ) => {
    startTransition(async () => {
      const result =
        action === "approve"
          ? await handleApproveLeaveRequest(employeeId, requestId)
          : 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>;
    }
    switch (request.requestType) {
        case 'leave':
            return request.from && request.to ? `${format(request.from, "MMM d, yyyy")} - ${format(request.to, "MMM d, yyyy")}` : 'N/A';
        case 'advance':
            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>
            );
        case 'shift-swap':
             return (
                 <div className="flex flex-col">
                    <div className="flex items-center gap-2">
                      <Repeat className="h-4 w-4 text-muted-foreground"/>
                      <span>{t.swapDetails.replace('{employeeName}', request.toEmployeeName || '')}</span>
                    </div>
                     {request.shiftDate && <span className="text-xs text-muted-foreground">{format(request.shiftDate, "MMM d, yyyy")}</span>}
                </div>
             );
        default:
            return <span className="text-muted-foreground italic">N/A</span>
    }
  }

  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" && request.requestType !== 'shift-swap' && (
                <div className="flex gap-2 justify-end">
                    <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleAction("approve", request.employeeId, request.id)}
                        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={() => handleAction("reject", 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>
              )}
               {request.status === "pending" && request.requestType === 'shift-swap' && (
                <div className="flex justify-end">
                  <span className="text-xs text-muted-foreground italic">{t.awaitingEmployeeApproval}</span>
                </div>
               )}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
