import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Card, Button, Spin, Typography, Tag, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  CreditCard,
  ArrowLeft,
  Building2,
  Calendar,
  Wallet,
  User,
  Mail,
  Receipt,
  Download,
  IndianRupee,
} from "lucide-react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import dayjs from "dayjs";

const { Title, Text } = Typography;

const formatCurrency = (amount: number) =>
  new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 2,
  }).format(amount || 0);

const PaymentDetailsPage: React.FC = () => {
  const { transactionId } = useParams<{ transactionId: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [payment, setPayment] = useState<any>(null);
  const [downloading, setDownloading] = useState(false);

  const fetchPaymentDetails = async () => {
    try {
      setLoading(true);
      const res = await API_Instance.get(`${API_Constants.payments}/${transactionId}`);
      setPayment(res.data.data);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (transactionId) {
      fetchPaymentDetails();
    }
  }, [transactionId]);

  const handleDownloadReceipt = async () => {
    if (!transactionId) return;

    try {
      setDownloading(true);
      const res = await API_Instance.get(
        `${API_Constants.payments}/${transactionId}/download-receipt`,
        {
          responseType: "blob",
        },
      );

      const fileURL = window.URL.createObjectURL(
        new Blob([res.data], { type: "application/pdf" }),
      );
      window.open(fileURL, "_blank");

      setTimeout(() => {
        window.URL.revokeObjectURL(fileURL);
      }, 1000);
    } catch (error) {
      toast.error("Failed to open receipt");
    } finally {
      setDownloading(false);
    }
  };

  const columns: ColumnsType<any> = [
    {
      title: "Student Name",
      key: "name",
      render: (_, record) => (
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-slate-100 rounded-full flex items-center justify-center text-slate-500">
            <User size={14} />
          </div>
          <span className="font-semibold text-slate-700">{record.name}</span>
        </div>
      ),
    },
    {
      title: "Email Address",
      dataIndex: "email",
      key: "email",
      render: (email) => (
        <div className="flex items-center gap-2 text-slate-500">
          <Mail size={14} />
          <span>{email || "N/A"}</span>
        </div>
      ),
    },
    {
      title: "Amount Charged",
      dataIndex: "amount",
      key: "amount",
      align: "right" as const,
      render: (amount) => (
        <span className="font-bold text-slate-900">
          {formatCurrency(Number(amount))}
        </span>
      ),
    },
  ];

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen bg-slate-50/50">
        <Spin size="large" tip="Loading transaction details..." />
      </div>
    );
  }

  if (!payment) {
    return (
      <div className="flex flex-col items-center justify-center h-screen gap-4">
        <Title level={4}>Transaction not found</Title>
        <Button onClick={() => navigate(ROUTE_CONSTANTS.Payments)}>Back to Payments</Button>
      </div>
    );
  }

  const getStatusConfig = (status: string) => {
    const config: Record<string, { color: string; label: string; gradient: string; iconColor: string }> = {
      SUCCESS: {
        color: "success",
        label: "Success",
        gradient: "from-emerald-600 to-teal-700",
        iconColor: "text-emerald-300",
      },
      PENDING: {
        color: "processing",
        label: "Pending",
        gradient: "from-blue-600 to-indigo-700",
        iconColor: "text-blue-300",
      },
      FAILED: {
        color: "error",
        label: "Failed",
        gradient: "from-rose-600 to-red-800",
        iconColor: "text-rose-300",
      },
      CANCELLED: {
        color: "error",
        label: "Cancelled",
        gradient: "from-slate-500 to-slate-700",
        iconColor: "text-slate-300",
      },
      EXPIRED: {
        color: "warning",
        label: "Expired",
        gradient: "from-amber-500 to-orange-700",
        iconColor: "text-amber-300",
      },
      REFUNDED: {
        color: "magenta",
        label: "Refunded",
        gradient: "from-purple-600 to-fuchsia-800",
        iconColor: "text-purple-300",
      },
      PARTIAL_REFUND: {
        color: "volcano",
        label: "Partial Refund",
        gradient: "from-orange-600 to-volcano-700",
        iconColor: "text-orange-300",
      },
    };
    return config[status] || {
      color: "default",
      label: status,
      gradient: "from-slate-600 to-slate-800",
      iconColor: "text-slate-300",
    };
  };

  const statusConfig = getStatusConfig(payment.status);
  const hasGst = Number(payment.gstRate || 0) > 0 && Number(payment.gstAmount || 0) > 0;
  const taxRows = hasGst
    ? payment.gstType === "IGST"
      ? [{ label: `IGST (${payment.gstRate}%)`, value: payment.igstAmount || payment.gstAmount }]
      : [
        { label: `CGST (${Number(payment.gstRate || 0) / 2}%)`, value: payment.cgstAmount },
        { label: `SGST (${Number(payment.gstRate || 0) / 2}%)`, value: payment.sgstAmount },
      ]
    : [];

  return (
    <div className="min-h-screen bg-slate-50/30 p-4 sm:p-6 lg:p-8">
      <div className="max-w-5xl mx-auto">
        <div className="mb-8 flex items-center gap-4">
          <Button
            type="text"
            icon={<ArrowLeft size={22} />}
            onClick={() => navigate(-1)}
            className="!w-12 !h-12 rounded-full bg-white shadow-sm border border-slate-200 text-slate-600 p-0 hover:bg-slate-50 hover:text-blue-600 hover:border-blue-200 transition-all shrink-0"
            title="Back to History"
            classNames={{ icon: "flex items-center justify-center" }}
          />
          <div>
            <h2 className="text-2xl font-black text-slate-800 m-0 tracking-tight">
              Payment Details
            </h2>
            <Text className="text-slate-500 text-sm font-medium flex items-center gap-1.5 mt-1">
              <CreditCard size={16} className="text-slate-400" /> Complete transaction summary and records
            </Text>
          </div>
          {payment.status === "SUCCESS" && (
            <Button
              type="primary"
              icon={<Download size={16} />}
              onClick={handleDownloadReceipt}
              loading={downloading}
              className="ml-auto flex items-center gap-2 bg-blue-600"
            >
              Receipt
            </Button>
          )}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
          <Card className="shadow-sm border-slate-200 rounded-3xl lg:col-span-2 overflow-hidden bg-white">
            <div className="p-6">
              <div className="flex justify-between items-start mb-6">
                <div>
                  <Text className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 block mb-1">
                    {payment.receiptNo ? "Receipt No" : "Order Reference"}
                  </Text>
                  <Title level={4} className="!m-0 !font-black !tracking-tight">
                    {payment.receiptNo || payment.transactionId || "N/A"}
                  </Title>
                </div>
                <Tag color={statusConfig.color} className="rounded-lg px-3 py-1 font-bold uppercase tracking-widest text-[10px] border-none shadow-sm">
                  {statusConfig.label}
                </Tag>
              </div>

              <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Date & Time
                  </Text>
                  <div className="flex items-center gap-2 text-slate-700 font-bold text-xs">
                    <Calendar size={14} className="text-blue-500" />
                    {dayjs(payment.date).format("DD MMM YYYY, hh:mm A")}
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Method
                  </Text>
                  <div className="flex items-center gap-2 text-slate-700 font-bold text-xs uppercase">
                    <CreditCard size={14} className="text-purple-500" />
                    {payment.paymentMethod || "N/A"}
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Plan
                  </Text>
                  <div className="flex items-center gap-2 text-slate-700 font-bold text-xs">
                    <Receipt size={14} className="text-orange-500" />
                    {payment.planName || "N/A"}
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Students
                  </Text>
                  <div className="flex items-center gap-2 text-slate-700 font-bold text-xs">
                    <User size={14} className="text-emerald-500" />
                    {payment.studentCount || 0}
                  </div>
                </div>
              </div>

              {payment.failureReason && (
                <div className="mt-6 p-4 bg-slate-50 border border-slate-100 rounded-2xl">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-rose-500 block mb-1">
                    Transaction Remarks
                  </Text>
                  <Text className="text-slate-600 text-xs font-medium italic leading-relaxed">
                    "{payment.failureReason}"
                  </Text>
                </div>
              )}
            </div>
          </Card>

          <Card className={`shadow-sm border-none rounded-3xl bg-gradient-to-br ${statusConfig.gradient} text-white overflow-hidden relative group`}>
            <div className="relative z-10 p-6 flex flex-col justify-between h-full">
              <div>
                <Text className="text-white/60 text-[10px] font-black uppercase tracking-[0.2em] mb-2 block">
                  {["REFUNDED", "PARTIAL_REFUND"].includes(payment.status) ? "Refunded Amount" :
                    ["FAILED", "CANCELLED", "EXPIRED"].includes(payment.status) ? "Attempted Amount" : "Total Amount Paid"}
                </Text>
                <Title level={2} className="!text-white !m-0 !font-black !tracking-tighter">
                  {formatCurrency(Number(payment.amount))}
                </Title>
              </div>
              <div className="mt-8 pt-6 border-t border-white/10 flex items-center gap-3">
                <div className={`w-10 h-10 ${statusConfig.iconColor.replace("text-", "bg-").replace("300", "400/20")} rounded-xl flex items-center justify-center ${statusConfig.iconColor} backdrop-blur-sm`}>
                  <Wallet size={20} />
                </div>
                <div>
                  <Text className="text-white font-bold text-[11px] block">
                    {payment.status === "SUCCESS" ? "Verified Transaction" : statusConfig.label}
                  </Text>
                  <Text className="text-white/50 text-[10px]">
                    {payment.status === "SUCCESS" ? "Tax Invoice Generated" : "Status tracked recorded"}
                  </Text>
                </div>
              </div>
            </div>
            <CreditCard size={180} className="absolute -bottom-10 -right-10 text-white/5 group-hover:scale-110 transition-transform duration-500" />
          </Card>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
          <Card className="shadow-sm border-slate-200 rounded-3xl overflow-hidden bg-white">
            <div className="p-6">
              <Title level={5} className="!m-0 !font-black !text-slate-700 flex items-center gap-2">
                <Building2 size={18} className="text-blue-500" />
                Institution Billing
              </Title>
              <div className="mt-5 grid grid-cols-1 sm:grid-cols-2 gap-5">
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Institution
                  </Text>
                  <Text className="text-slate-700 font-bold text-sm">
                    {payment.institution || "N/A"}
                  </Text>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Email
                  </Text>
                  <Text className="text-slate-700 font-bold text-sm break-all">
                    {payment.institutionEmail || "N/A"}
                  </Text>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    GSTIN
                  </Text>
                  <Text className="text-slate-700 font-bold text-sm">
                    {payment.institutionGstNumber || payment.customerGstNumber || "N/A"}
                  </Text>
                </div>
                <div className="flex flex-col gap-1">
                  <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Transaction ID
                  </Text>
                  <Text className="text-slate-700 font-bold text-sm break-all">
                    {payment.transactionId || "N/A"}
                  </Text>
                </div>
              </div>
              <div className="mt-5 flex flex-col gap-1">
                <Text className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                  Address
                </Text>
                <Text className="text-slate-600 text-sm leading-relaxed">
                  {payment.institutionAddress || "N/A"}
                </Text>
              </div>
            </div>
          </Card>

          <Card className="shadow-sm border-slate-200 rounded-3xl overflow-hidden bg-white">
            <div className="p-6">
              <Title level={5} className="!m-0 !font-black !text-slate-700 flex items-center gap-2">
                <IndianRupee size={18} className="text-emerald-500" />
                Amount & Tax Details
              </Title>
              <div className="mt-5 space-y-3">
                <div className="flex items-center justify-between gap-4">
                  <Text className="text-slate-500 text-sm">Taxable Amount</Text>
                  <Text className="text-slate-800 font-bold">
                    {formatCurrency(Number(payment.taxableAmount || payment.amount || 0))}
                  </Text>
                </div>
                {taxRows.length > 0 ? (
                  taxRows.map((row) => (
                    <div key={row.label} className="flex items-center justify-between gap-4">
                      <Text className="text-slate-500 text-sm">{row.label}</Text>
                      <Text className="text-slate-800 font-bold">
                        {formatCurrency(Number(row.value || 0))}
                      </Text>
                    </div>
                  ))
                ) : (
                  <div className="flex items-center justify-between gap-4">
                    <Text className="text-slate-500 text-sm">GST</Text>
                    <Text className="text-slate-400 font-bold">No GST</Text>
                  </div>
                )}
                <div className="pt-3 mt-3 border-t border-slate-100 flex items-center justify-between gap-4">
                  <Text className="text-slate-700 font-black">Grand Total</Text>
                  <Text className="text-emerald-600 font-black text-lg">
                    {formatCurrency(Number(payment.amount || 0))}
                  </Text>
                </div>
              </div>
            </div>
          </Card>
        </div>

        <Card className="shadow-sm border-slate-200 rounded-[2rem] overflow-hidden bg-white">
          <div className="p-6 border-b border-slate-50 flex items-center justify-between bg-slate-50/50">
            <Title level={5} className="!m-0 !font-black !text-slate-700 flex items-center gap-2">
              Itemized Students List
            </Title>
            <Text className="text-[11px] font-bold text-slate-400 uppercase tracking-widest">
              {(payment.students || []).length} Records found
            </Text>
          </div>
          <Table
            columns={columns}
            dataSource={payment.students || []}
            rowKey="id"
            pagination={(payment.students || []).length > 10 ? { pageSize: 15 } : false}
            className="custom-table"
          />
        </Card>
      </div>
    </div>
  );
};

export default PaymentDetailsPage;
