"use client";

import { useEffect, useState } from "react";

import axios from "axios";

import Cookies from "js-cookie";

import { Button } from "@/components/shadcnui/button";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/shadcnui/card";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/shadcnui/select";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/shadcnui/table";
import toast, { Toaster } from "react-hot-toast";

interface PayoutType {
  _id: string;

  walletId: string;

  amount: number;

  status: string;

  createdAt: string;

  approvedAt?: string;

  approvedBy?: string;

  userId: {
    _id: string;

    name: string;

    mobile: string;

    role: string;
  };
}

const payoutStatusFlow: Record<string, string[]> = {
  PENDING: ["APPROVED", "REJECTED"],

  APPROVED: [],

  REJECTED: [],
};

const PayoutRequestPage = () => {
  const token = Cookies.get("kero_token");

  const [loadingId, setLoadingId] = useState("");

  const [payoutList, setPayoutList] = useState<PayoutType[]>([]);

  const [selectedStatus, setSelectedStatus] = useState<Record<string, string>>(
    {},
  );

  const getAllPayouts = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/wallet/payouts/all`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        setPayoutList(response.data.payouts);

        const statusMap: Record<string, string> = {};

        response.data.payouts.forEach((item: PayoutType) => {
          statusMap[item._id] = item.status;
        });

        setSelectedStatus(statusMap);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getAllPayouts();
  }, []);

  const updatePayoutStatus = async (id: string) => {
    try {
      setLoadingId(id);

      const response = await axios.patch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/wallet/payout/${id}`,
        {
          status: selectedStatus[id],
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        toast.success("Payout status updated!");
        getAllPayouts();
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoadingId("");
    }
  };

  return (
    <div className="mt-6 space-y-6">
      <Toaster
        position="top-center"
        reverseOrder={false}
      />
      {payoutList.map((item) => (
        <Card key={item._id}>
          <CardHeader className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div className="space-y-1">
              <CardTitle className="text-xl">
                {item.userId?.name || "No User"}
              </CardTitle>

              <p>Mobile: {item.userId?.mobile || "-"}</p>

              <p>Role: {item.userId?.role || "-"}</p>

              <p>Payout ID: {item._id}</p>
            </div>

            <div className="flex w-full flex-col gap-3 lg:w-72">
              <Select
                disabled={
                  item.status === "APPROVED" || item.status === "REJECTED"
                }
                value={selectedStatus[item._id] || item.status}
                onValueChange={(value) => {
                  if (!value) return;

                  setSelectedStatus((prev) => ({
                    ...prev,

                    [item._id]: value,
                  }));
                }}>
                <SelectTrigger>
                  <SelectValue placeholder="Select Status" />
                </SelectTrigger>

                <SelectContent>
                  {payoutStatusFlow[item.status]?.map((status) => (
                    <SelectItem
                      key={status}
                      value={status}>
                      {status}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Button
                onClick={() => updatePayoutStatus(item._id)}
                disabled={
                  loadingId === item._id ||
                  item.status === "APPROVED" ||
                  item.status === "REJECTED"
                }>
                {loadingId === item._id ?
                  "Updating..."
                : item.status === "APPROVED" || item.status === "REJECTED" ?
                  "Status Locked"
                : "Update Payout Status"}
              </Button>
            </div>
          </CardHeader>

          <CardContent className="space-y-6">
            <div className="grid grid-cols-1 gap-4 md:grid-cols-3 lg:grid-cols-5">
              <div>
                <p className="text-muted-foreground text-sm">Amount</p>

                <p className="font-medium">₹ {item.amount}</p>
              </div>

              <div>
                <p className="text-muted-foreground text-sm">Status</p>

                <p className="font-medium">{item.status}</p>
              </div>

              <div>
                <p className="text-muted-foreground text-sm">Wallet ID</p>

                <p className="font-medium break-all">{item.walletId}</p>
              </div>

              <div>
                <p className="text-muted-foreground text-sm">Created At</p>

                <p className="font-medium">
                  {new Date(item.createdAt).toLocaleString()}
                </p>
              </div>

              <div>
                <p className="text-muted-foreground text-sm">Approved At</p>

                <p className="font-medium">
                  {item.approvedAt ?
                    new Date(item.approvedAt).toLocaleString()
                  : "-"}
                </p>
              </div>
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>User Name</TableHead>

                  <TableHead>Mobile</TableHead>

                  <TableHead>Role</TableHead>

                  <TableHead>Amount</TableHead>

                  <TableHead>Status</TableHead>

                  <TableHead>Created</TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                <TableRow>
                  <TableCell>{item.userId?.name || "-"}</TableCell>

                  <TableCell>{item.userId?.mobile || "-"}</TableCell>

                  <TableCell>{item.userId?.role || "-"}</TableCell>

                  <TableCell>₹ {item.amount}</TableCell>

                  <TableCell>{item.status}</TableCell>

                  <TableCell>
                    {new Date(item.createdAt).toLocaleString()}
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ))}
    </div>
  );
};

export default PayoutRequestPage;
