"use client";

import { useEffect, useState } from "react";

import axios from "axios";

import Cookies from "js-cookie";

import Image from "next/image";

import { Download } from "lucide-react";

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

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

import { Input } from "@/components/shadcnui/input";

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

interface CouponType {
  _id: string;

  code: string;

  value: number;

  points: number;

  status: string;

  qrCode: string;

  createdAt: string;

  redeemedAt?: string;

  redeemedBy?: {
    name: string;

    mobile: string;

    role: string;
  };
}

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

  const [couponList, setCouponList] = useState<CouponType[]>([]);

  const [loading, setLoading] = useState(false);

  const [page, setPage] = useState(1);

  const [limit, setLimit] = useState(10);

  const [totalPages, setTotalPages] = useState(1);

  const [formData, setFormData] = useState({
    code: "",

    value: "",
  });

  const getAllCoupons = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/coupons/all?page=${page}&limit=${limit}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        setCouponList(response.data.data);

        setTotalPages(response.data.pagination.totalPages);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getAllCoupons();
  }, [page, limit]);

  const createCoupon = async () => {
    try {
      setLoading(true);

      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/coupons/create`,
        {
          code: formData.code,

          value: Number(formData.value),
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        setFormData({
          code: "",

          value: "",
        });

        toast.success("Cuppon created!");
        getAllCoupons();
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  const downloadQRCode = (qrCode: string, code: string) => {
    const link = document.createElement("a");

    link.href = qrCode;

    link.download = `${code}-qr.png`;

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
  };

  return (
    <div className="mt-6 space-y-8">
      <Toaster
        position="top-center"
        reverseOrder={false}
      />
      <Card>
        <CardHeader>
          <CardTitle>Create Coupon</CardTitle>
        </CardHeader>

        <CardContent>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <Input
              placeholder="Coupon Code"
              value={formData.code}
              onChange={(e) =>
                setFormData((prev) => ({
                  ...prev,

                  code: e.target.value,
                }))
              }
            />

            <Input
              type="number"
              placeholder="Coupon Value"
              value={formData.value}
              onChange={(e) =>
                setFormData((prev) => ({
                  ...prev,

                  value: e.target.value,
                }))
              }
            />

            <Button
              onClick={createCoupon}
              disabled={loading}>
              {loading ? "Creating..." : "Create Coupon"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>All Coupons</CardTitle>

          <div className="flex items-center gap-3">
            <select
              value={limit}
              onChange={(e) => {
                setLimit(Number(e.target.value));

                setPage(1);
              }}
              className="rounded-md border px-3 py-2 text-sm">
              <option value={5}>5</option>

              <option value={10}>10</option>

              <option value={20}>20</option>

              <option value={50}>50</option>
            </select>
          </div>
        </CardHeader>

        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>QR</TableHead>

                <TableHead>Code</TableHead>

                <TableHead>Value</TableHead>

                <TableHead>Points</TableHead>

                <TableHead>Status</TableHead>

                <TableHead>Redeemed By</TableHead>

                <TableHead>Role</TableHead>

                <TableHead>Created At</TableHead>

                <TableHead>Action</TableHead>
              </TableRow>
            </TableHeader>

            <TableBody>
              {couponList.map((item) => (
                <TableRow key={item._id}>
                  <TableCell>
                    {item.qrCode?.startsWith("data:image") ?
                      <Image
                        src={item.qrCode}
                        alt="QR"
                        width={70}
                        height={70}
                        className="rounded-md border object-cover"
                      />
                    : <div className="rounded-md border px-3 py-2 text-xs">
                        No QR
                      </div>
                    }
                  </TableCell>

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

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

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

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

                  <TableCell>{item.redeemedBy?.name || "-"}</TableCell>

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

                  <TableCell>
                    {new Date(item.createdAt).toLocaleString()}
                  </TableCell>

                  <TableCell>
                    {item.qrCode?.startsWith("data:image") && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => downloadQRCode(item.qrCode, item.code)}>
                        <Download className="mr-2 h-4 w-4" />
                        Download
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          <div className="mt-6 flex items-center justify-between">
            <Button
              variant="outline"
              disabled={page === 1}
              onClick={() => setPage((prev) => prev - 1)}>
              Previous
            </Button>

            <p className="text-sm">
              Page {page} of {totalPages}
            </p>

            <Button
              variant="outline"
              disabled={page === totalPages}
              onClick={() => setPage((prev) => prev + 1)}>
              Next
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default CouponPage;
