"use client";
import {
  createContext,
  useContext,
  useState,
  useCallback,
  useMemo,
} from "react";
import type { PaymentOrder, PaymentMethod, BuyerInfo } from "@/components/payments/types";
import { MOCK_ORDERS, CHECKOUT_ITEM } from "@/components/payments/mockData";

export interface BuyNowOrderParams {
  listingId: string;
  listingSlug: string;
  listingTitle: string;
  listingImage: string;
  sellerId: string;
  sellerName: string;
  sellerAvatar: string;
  price: number;
  transactionId: string;
}

interface PaymentCtx {
  orders: PaymentOrder[];
  pendingOrder: PaymentOrder | null;
  initiateCheckout: (listingSlug: string) => void;
  updateBuyerInfo: (info: BuyerInfo) => void;
  selectPaymentMethod: (method: PaymentMethod) => void;
  placeOrder: () => PaymentOrder | null;
  confirmCOD: (orderId: string) => void;
  rejectCOD: (orderId: string) => void;
  requestRefund: (orderId: string, reason: string) => void;
  recordBuyNowOrder: (params: BuyNowOrderParams) => PaymentOrder;
  selectedMethod: PaymentMethod;
  buyerInfo: BuyerInfo;
  lastCompletedOrder: PaymentOrder | null;
}

const defaultBuyerInfo: BuyerInfo = {
  name: "Keyur Ramani",
  email: "keyur@divinetechs.com",
  phone: "+91 98765 43210",
  address: "42, Sunrise Apartments, Andheri West",
  city: "Mumbai",
  pincode: "400053",
};

const PaymentContext = createContext<PaymentCtx>({
  orders: [],
  pendingOrder: null,
  initiateCheckout: () => {},
  updateBuyerInfo: () => {},
  selectPaymentMethod: () => {},
  placeOrder: () => null,
  confirmCOD: () => {},
  rejectCOD: () => {},
  requestRefund: () => {},
  recordBuyNowOrder: () => {
    throw new Error("recordBuyNowOrder called outside PaymentProvider");
  },
  selectedMethod: "paypal",
  buyerInfo: defaultBuyerInfo,
  lastCompletedOrder: null,
});

let orderCounter = 100;

export function PaymentProvider({ children }: { children: React.ReactNode }) {
  const [orders, setOrders] = useState<PaymentOrder[]>(MOCK_ORDERS);
  const [selectedMethod, setSelectedMethod] = useState<PaymentMethod>("paypal");
  const [buyerInfo, setBuyerInfo] = useState<BuyerInfo>(defaultBuyerInfo);
  const [lastCompletedOrder, setLastCompletedOrder] = useState<PaymentOrder | null>(null);

  const initiateCheckout = useCallback((_listingSlug: string) => {
    // In real app: fetch listing data and prepare order
  }, []);

  const updateBuyerInfo = useCallback((info: BuyerInfo) => {
    setBuyerInfo(info);
  }, []);

  const selectPaymentMethod = useCallback((method: PaymentMethod) => {
    setSelectedMethod(method);
  }, []);

  const placeOrder = useCallback((): PaymentOrder | null => {
    const now = new Date().toISOString();
    const newOrder: PaymentOrder = {
      ...CHECKOUT_ITEM,
      id: `ord-${++orderCounter}`,
      buyerId: "me",
      buyerInfo,
      paymentMethod: selectedMethod,
      paymentStatus: "pending",
      orderStatus:
        selectedMethod === "paypal" ? "awaiting_payment" : "awaiting_confirmation",
      createdAt: now,
      updatedAt: now,
      transactionId:
        selectedMethod === "paypal"
          ? `PAY-${Math.random().toString(36).substring(2, 10).toUpperCase()}`
          : undefined,
    };
    setOrders((prev) => [newOrder, ...prev]);
    setLastCompletedOrder(newOrder);
    return newOrder;
  }, [buyerInfo, selectedMethod]);

  const confirmCOD = useCallback((orderId: string) => {
    const now = new Date().toISOString();
    setOrders((prev) =>
      prev.map((o) =>
        o.id === orderId
          ? {
              ...o,
              paymentStatus: "paid" as const,
              orderStatus: "completed" as const,
              transactionId: `COD-${Date.now()}`,
              updatedAt: now,
            }
          : o
      )
    );
  }, []);

  const rejectCOD = useCallback((orderId: string) => {
    const now = new Date().toISOString();
    setOrders((prev) =>
      prev.map((o) =>
        o.id === orderId
          ? {
              ...o,
              paymentStatus: "cancelled" as const,
              orderStatus: "cancelled" as const,
              updatedAt: now,
            }
          : o
      )
    );
  }, []);

  const recordBuyNowOrder = useCallback(
    (params: BuyNowOrderParams): PaymentOrder => {
      const now = new Date().toISOString();
      const newOrder: PaymentOrder = {
        id: `ord-${++orderCounter}`,
        listingId: params.listingId,
        listingSlug: params.listingSlug,
        listingTitle: params.listingTitle,
        listingImage: params.listingImage,
        listingCondition: "",
        sellerId: params.sellerId,
        sellerName: params.sellerName,
        sellerAvatar: params.sellerAvatar,
        sellerVerified: false,
        buyerId: "me",
        buyerInfo,
        quantity: 1,
        listingPrice: params.price,
        serviceFee: 0,
        deliveryFee: 0,
        discount: 0,
        tax: 0,
        totalAmount: params.price,
        paymentMethod: "paypal",
        paymentStatus: "paid",
        orderStatus: "confirmed",
        transactionId: params.transactionId,
        createdAt: now,
        updatedAt: now,
      };
      setOrders((prev) => [newOrder, ...prev]);
      setLastCompletedOrder(newOrder);
      return newOrder;
    },
    [buyerInfo],
  );

  const requestRefund = useCallback((orderId: string, reason: string) => {
    const now = new Date().toISOString();
    setOrders((prev) =>
      prev.map((o) =>
        o.id === orderId
          ? {
              ...o,
              refundStatus: "requested" as const,
              refundReason: reason,
              updatedAt: now,
            }
          : o
      )
    );
  }, []);

  const pendingOrder = useMemo(
    () =>
      orders.find((o) => o.buyerId === "me" && o.paymentStatus === "pending") ?? null,
    [orders]
  );

  const value = useMemo(
    () => ({
      orders,
      pendingOrder,
      initiateCheckout,
      updateBuyerInfo,
      selectPaymentMethod,
      placeOrder,
      confirmCOD,
      rejectCOD,
      requestRefund,
      recordBuyNowOrder,
      selectedMethod,
      buyerInfo,
      lastCompletedOrder,
    }),
    [
      orders,
      pendingOrder,
      initiateCheckout,
      updateBuyerInfo,
      selectPaymentMethod,
      placeOrder,
      confirmCOD,
      rejectCOD,
      requestRefund,
      recordBuyNowOrder,
      selectedMethod,
      buyerInfo,
      lastCompletedOrder,
    ]
  );

  return (
    <PaymentContext.Provider value={value}>{children}</PaymentContext.Provider>
  );
}

export const usePayment = () => useContext(PaymentContext);
