"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 Image from "next/image";

interface OrderItemType {
  quantity: number;

  price: number;

  totalPrice: number;

  orderType?: string;

  designName?: string;

  size?: string;

  sqFt?: number;

  calculatedPrice?: number;

  productSnapshot?: {
    name?: string;

    imageUrl?: string;

    sku?: string;
  };
}
interface OrderType {
  _id: string;

  role: string;

  status: string;

  totalAmount: number;

  gstAmount: number;

  discountAmount: number;

  finalAmount: number;

  note: string;

  createdAt: string;

  userId: {
    name: string;

    mobile: string;

    role: string;
  };

  items: OrderItemType[];
}

const statusFlow: Record<string, string[]> = {
  PLACED: ["ACCEPTED", "CANCELLED"],

  ACCEPTED: ["COMPLETED"],

  COMPLETED: [],

  CANCELLED: [],
};

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

  const [orders, setOrders] = useState<OrderType[]>([]);

  const [loading, setLoading] = useState<string | null>(null);

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

  const getAllOrders = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/orders/admin`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        setOrders(response.data.orders);
      }
    } catch (error) {
      console.log(error);
    }
  };

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

  const updateOrderStatus = async (orderId: string, status: string) => {
    try {
      setLoading(orderId);

      await axios.patch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/orders/${orderId}/status`,
        {
          status,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      getAllOrders();
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(null);
    }
  };

  return (
    <div className="mt-6 space-y-6">
      {orders.map((order) => (
        <Card key={order._id}>
          <CardHeader className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
            <div>
              <CardTitle>Order ID: {order._id.slice(-8)}</CardTitle>

              <p className="text-muted-foreground mt-2 text-sm">
                Customer: {order.userId?.name}
              </p>

              <p className="text-muted-foreground text-sm">
                Mobile: {order.userId?.mobile}
              </p>
            </div>

            <div className="w-full max-w-80 space-y-3">
              <Select
                disabled={
                  order.status === "COMPLETED" || order.status === "CANCELLED"
                }
                value={selectedStatus[order._id] || order.status}
                onValueChange={(value) =>
                  setSelectedStatus((prev) => ({
                    ...prev,
                    [order._id]: value,
                  }))
                }>
                <SelectTrigger>
                  <SelectValue placeholder="Select Status" />
                </SelectTrigger>

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

              <Button
                className="w-full"
                disabled={
                  loading === order._id ||
                  order.status === "COMPLETED" ||
                  order.status === "CANCELLED"
                }
                onClick={() =>
                  updateOrderStatus(
                    order._id,
                    selectedStatus[order._id] || order.status,
                  )
                }>
                {loading === order._id ?
                  "Updating..."
                : order.status === "COMPLETED" || order.status === "CANCELLED" ?
                  "Status Locked"
                : "Update Status"}
              </Button>
            </div>
          </CardHeader>

          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
              <div>
                <p className="text-muted-foreground text-sm">Order Status</p>

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

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

                <p className="font-medium">₹ {order.totalAmount}</p>
              </div>

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

                <p className="font-medium">₹ {order.gstAmount}</p>
              </div>

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

                <p className="font-medium">₹ {order.finalAmount}</p>
              </div>
            </div>

            <div>
              <p className="text-muted-foreground mb-2 text-sm">Note</p>

              <div className="rounded-xl border p-4">{order.note || "-"}</div>
            </div>

            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Image</TableHead>

                    <TableHead>Product</TableHead>

                    <TableHead>SKU</TableHead>

                    <TableHead>Quantity</TableHead>

                    <TableHead>Price</TableHead>

                    <TableHead>Total</TableHead>
                  </TableRow>
                </TableHeader>

                <TableBody>
                  {order.items.map((item, index) => {
                    const isTile = item.orderType === "TILE";

                    const imageUrl =
                      item.productSnapshot?.imageUrl ?
                        `http://app.keroindia.com${item.productSnapshot.imageUrl}`
                      : "/images/no-image.png"; // add placeholder image in public/images

                    return (
                      <TableRow key={index}>
                        <TableCell>
                          {item.productSnapshot?.imageUrl ?
                            <Image
                              src={imageUrl}
                              alt={item.productSnapshot?.name || "Product"}
                              width={60}
                              height={60}
                              className="rounded-md object-cover"
                            />
                          : <div className="flex h-[60px] w-[60px] items-center justify-center rounded-md bg-slate-100 text-2xl">
                              🧱
                            </div>
                          }
                        </TableCell>

                        <TableCell>
                          {isTile ?
                            item.designName
                          : item.productSnapshot?.name || "-"}
                        </TableCell>

                        <TableCell>
                          {isTile ?
                            item.size || "-"
                          : item.productSnapshot?.sku || "-"}
                        </TableCell>

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

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

                        <TableCell>₹ {item.totalPrice}</TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>

            <div className="grid grid-cols-1 gap-4 border-t pt-5 md:grid-cols-3">
              <div>
                <p className="text-muted-foreground text-sm">Customer Role</p>

                <p className="font-medium">{order.role}</p>
              </div>

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

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

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

                <p className="font-medium">₹ {order.discountAmount}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
};

export default OrderForm;
