import { History, ArrowLeft, Calendar, Trash2 } from "lucide-react";
import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Table,
  Card,
  Button,
  Pagination,
  Tag,
  Typography,
  Popconfirm,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { API_Instance } from "../../api/axios.instance";
import API_Constants from "../../constants/api.constants";
import { ISubscriptionPlan } from "../../types";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import dayjs from "dayjs";

export default function SubscriptionHistory() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [history, setHistory] = useState<ISubscriptionPlan[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);

  const fetchHistory = async (p = 1, l = 10) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(API_Constants.subscriptionHistory, {
        params: {
          planType: slug,
          page: p,
          limit: l,
        },
      });
      setHistory(res.data.data);
      setTotal(res.data.meta.total);
      setPage(res.data.meta.page);
      setLimit(res.data.meta.limit);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await API_Instance.delete(`${API_Constants.subscriptionPlans}/${id}`);
      toast.success("Plan deleted successfully");
      fetchHistory(page, limit);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    }
  };

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

  const columns: ColumnsType<ISubscriptionPlan> = [
    {
      title: "Plan Name",
      dataIndex: "planName",
      key: "planName",
      render: (text) => <span className="font-semibold">{text}</span>,
    },
    {
      title: "Pricing Details",
      key: "pricing",
      render: (_, record) => (
        <div className="flex flex-col gap-1 text-xs">
          <div className="flex items-center gap-2">
            <span className="text-slate-400 line-through">
              ₹{record.actualPrice}
            </span>
            <Tag color="green" className="m-0 px-1 py-0 text-[10px]">
              -{record.discountPercentage}%
            </Tag>
          </div>
          <div className="text-sm font-medium text-slate-700">
            ₹{record.basicPrice}{" "}
            <span className="text-xs text-slate-400">
              + {record.gstPercentage}% GST
            </span>
          </div>
        </div>
      ),
    },
    {
      title: "Final Price",
      dataIndex: "finalPrice",
      key: "finalPrice",
      render: (price) => (
        <span className="text-blue-600 font-bold">
          ₹{Number(price).toFixed(2)}
        </span>
      ),
    },
    {
      title: "Duration",
      dataIndex: "duration",
      key: "duration",
      render: (days) => `${days} Days`,
    },
    {
      title: "Status",
      dataIndex: "isActive",
      key: "isActive",
      render: (isActive) => (
        <Tag color={isActive ? "success" : "default"} className="rounded-full">
          {isActive ? "Active" : "Archived"}
        </Tag>
      ),
    },
    {
      title: "Updated At",
      dataIndex: "updatedAt",
      key: "updatedAt",
      render: (date) => (
        <div className="flex items-center gap-2 text-slate-500 text-xs italic">
          <Calendar size={14} className="text-slate-400" />
          {date ? dayjs(date).format("DD MMM YYYY, hh:mm A") : "N/A"}
        </div>
      ),
    },
    {
      title: "Actions",
      key: "actions",
      render: (_, record) => (
        <Popconfirm
          title="Delete this historical record?"
          description="Are you sure you want to delete this specific version? This action cannot be undone."
          onConfirm={() => handleDelete(record.id)}
          okText="Yes, Delete"
          cancelText="No"
          okButtonProps={{ danger: true }}
        >
          <Button
            type="text"
            danger
            icon={<Trash2 size={18} />}
            className="flex items-center justify-center hover:bg-red-50"
          />
        </Popconfirm>
      ),
    },
  ];

  return (
    <div className="mx-auto px-6 py-6 max-w-[1600px]">
      {/* HEADER */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
        <div className="flex items-center gap-4">
          <div>
            <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-3">
              <div className="p-2 bg-blue-50 text-blue-600 rounded-xl">
                <History size={24} />
              </div>
              {slug ? slug.charAt(0).toUpperCase() + slug.slice(1) : "Pack"}{" "}
              History
            </h2>
            <p className="text-slate-500 text-sm mt-1">
              View previous versions and updates of the {slug} subscription
              pack.
            </p>
          </div>
        </div>
      </div>

      <Card className="shadow-sm border border-slate-200 rounded-xl overflow-hidden">
        <div className="flex flex-col md:flex-row justify-between items-center gap-4 mb-6">
          <h3 className="text-lg font-semibold text-slate-800">History Log</h3>
          <div className="text-slate-500 text-sm bg-slate-50 px-3 py-1 rounded-full border border-slate-100">
            Total Records:{" "}
            <span className="font-semibold text-slate-800">{total}</span>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={history}
          loading={loading}
          pagination={false}
          rowKey="id"
          scroll={{ x: 800 }}
          className="border border-slate-100 rounded-lg"
        />

        <div className="flex justify-end mt-6">
          <Pagination
            current={page}
            total={total}
            pageSize={limit}
            onChange={(p, pageSize) => {
              setPage(p);
              setLimit(pageSize);
              fetchHistory(p, pageSize);
            }}
            showSizeChanger
            showTotal={(total) => `Total ${total} items`}
            className="bg-white p-2 rounded-lg"
          />
        </div>
      </Card>
    </div>
  );
}
