import React, { useState, useEffect, useContext } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Container, Row, Col, Card, Button, Form, Badge } from "react-bootstrap";
import { FaShoppingCart, FaCreditCard, FaUser, FaInfoCircle } from "react-icons/fa";
import axiosInstance from "../../utils/axiosInstance";
import { AuthContext } from "../../context/AuthContext";
import "./Payment.css";

const Checkout = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const { userLogin, token, daftarKursus } = useContext(AuthContext);

  const [step, setStep] = useState(1);
  const [qty, setQty] = useState(1);
  const [produk, setProduk] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let script = null;
    if (!document.getElementById('midtrans-snap-script')) {
      script = document.createElement("script");
      script.id = "midtrans-snap-script";
      script.src = "https://app.sandbox.midtrans.com/snap/snap.js";
      script.setAttribute(
        "data-client-key",
        import.meta.env.VITE_MIDTRANS_CLIENT_KEY || "SB-Mid-client-XXXXX"
      );
      script.async = true;
      document.body.appendChild(script);
    }

    return () => {
      if (script && document.body.contains(script)) {
        document.body.removeChild(script);
      }
    };
  }, []);

  useEffect(() => {
    if (daftarKursus && daftarKursus.length > 0) {
      const found = daftarKursus.find((k) => k.id === parseInt(id));
      if (found) {
        setProduk(found);
      } else {
        navigate("/courses");
      }
      setLoading(false);
    }
  }, [id, daftarKursus, navigate]);

  const totalHarga = produk ? produk.harga * qty : 0;

  const handleLanjutPembayaran = (e) => {
    e.preventDefault();
    setStep(2);
  };

  const handleBayar = async () => {
    try {
      const resPesanan = await axiosInstance.post("/orders", {
        productId: produk.id,
        totalPrice: totalHarga
      });

      const orderId = resPesanan.data.orderId;

      const savedUser = JSON.parse(localStorage.getItem("userLogin") || "{}");
      const emailUser = savedUser.email || userLogin?.email || "user@example.com";

      const resSnap = await axiosInstance.post("/orders/snap-token", {
        orderId: orderId,
        total: totalHarga,
        customerDetails: {
          name: userLogin?.nama || "Pelanggan",
          email: emailUser,
        }
      });

      const snapToken = resSnap.data.token;

      window.snap.pay(snapToken, {
        onSuccess: (result) => {
          navigate(
            `/checkout/selesai?order_id=${result.order_id}&transaction_status=${result.transaction_status}&pesanan_id=${orderId}`
          );
        },
        onPending: (result) => {
          navigate(
            `/checkout/selesai?order_id=${result.order_id}&transaction_status=pending&pesanan_id=${orderId}`
          );
        },
        onError: (result) => {
          alert("Pembayaran Gagal! Silakan coba lagi.");
          console.error(result);
        },
        onClose: () => {
          console.log("Popup Midtrans ditutup oleh pengguna");
        }
      });
    } catch (error) {
      console.error("Kesalahan pembayaran:", error?.response);
      alert(error?.response?.data?.message || "Terjadi kesalahan saat memproses pembayaran");
    }
  };

  if (loading) {
    return (
      <Container className="py-5 text-center">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
        <p className="mt-3">Memuat detail kursus...</p>
      </Container>
    );
  }

  if (!produk) {
    return (
      <Container className="py-5 text-center">
        <h3>Kursus tidak ditemukan</h3>
        <Button onClick={() => navigate("/courses")}>Kembali ke Kursus</Button>
      </Container>
    );
  }

  return (
    <div className="checkout-page py-5">
      <Container>
        <div className="d-flex justify-content-between align-items-center mb-4">
          <h2 className="fw-bold">Checkout</h2>
          <div className="step-indicator">
            <Badge bg={step === 1 ? "primary" : "secondary"} className="me-2">1. Informasi</Badge>
            <Badge bg={step === 2 ? "primary" : "secondary"}>2. Pembayaran</Badge>
          </div>
        </div>

        <Row>
          <Col lg={7}>
            <Card className="shadow-sm border-0 mb-4">
              <Card.Body className="p-4">
                {step === 1 ? (
                  <div className="step-content">
                    <h5 className="mb-4 d-flex align-items-center gap-2">
                      <FaUser className="text-primary" /> Informasi Pembeli
                    </h5>
                    <Form onSubmit={handleLanjutPembayaran}>
                      <Form.Group className="mb-3">
                        <Form.Label>Nama Lengkap</Form.Label>
                        <Form.Control type="text" value={userLogin?.nama || ""} disabled />
                      </Form.Group>
                      
                      <div className="qty-selector mb-4">
                        <Form.Label>Jumlah Tiket/Akses</Form.Label>
                        <div className="d-flex align-items-center gap-3">
                          <Button 
                            variant="outline-secondary" 
                            size="sm"
                            onClick={() => setQty(q => Math.max(1, q - 1))}
                          >-</Button>
                          <span className="fw-bold fs-5">{qty}</span>
                          <Button 
                            variant="outline-secondary" 
                            size="sm"
                            onClick={() => setQty(q => q + 1)}
                          >+</Button>
                        </div>
                      </div>

                      <Button variant="primary" type="submit" className="w-100 py-2">
                        Lanjut ke Pembayaran
                      </Button>
                    </Form>
                  </div>
                ) : (
                  <div className="step-content">
                    <h5 className="mb-4 d-flex align-items-center gap-2">
                      <FaCreditCard className="text-primary" /> Konfirmasi Pembayaran
                    </h5>
                    <div className="payment-summary p-3 bg-light rounded mb-4">
                      <div className="d-flex justify-content-between mb-2">
                        <span>Pembeli:</span>
                        <span className="fw-bold">{userLogin?.nama}</span>
                      </div>
                      <div className="d-flex justify-content-between mb-2">
                        <span>Produk:</span>
                        <span className="fw-bold">{produk.judul}</span>
                      </div>
                      <div className="d-flex justify-content-between">
                        <span>Total Bayar:</span>
                        <span className="fw-bold text-primary fs-5">
                          Rp {totalHarga.toLocaleString("id-ID")}
                        </span>
                      </div>
                    </div>
                    
                    <div className="d-flex gap-2">
                      <Button variant="outline-secondary" onClick={() => setStep(1)} className="flex-grow-1">
                        Kembali
                      </Button>
                      <Button variant="primary" onClick={handleBayar} className="flex-grow-2 w-100">
                        Bayar Sekarang
                      </Button>
                    </div>
                  </div>
                )}
              </Card.Body>
            </Card>
          </Col>

          <Col lg={5}>
            <Card className="shadow-sm border-0 sticky-top" style={{ top: '2rem' }}>
              <Card.Body className="p-4">
                <h5 className="mb-4 d-flex align-items-center gap-2">
                  <FaShoppingCart className="text-primary" /> Ringkasan Pesanan
                </h5>
                <div className="d-flex gap-3 mb-3">
                  <img 
                    src={produk.thumbnail} 
                    alt={produk.judul}
                    className="rounded"
                    style={{ width: '80px', height: '80px', objectFit: 'cover' }}
                  />
                  <div>
                    <h6 className="mb-1">{produk.judul}</h6>
                    <small className="text-muted">{produk.kategori}</small>
                  </div>
                </div>
                <hr />
                <div className="d-flex justify-content-between mb-2">
                  <span>Harga</span>
                  <span>Rp {produk.harga?.toLocaleString("id-ID")}</span>
                </div>
                <div className="d-flex justify-content-between mb-2">
                  <span>Kuantitas</span>
                  <span>x{qty}</span>
                </div>
                <hr />
                <div className="d-flex justify-content-between align-items-center">
                  <span className="fw-bold">Total</span>
                  <span className="fw-bold text-primary fs-4">
                    Rp {totalHarga.toLocaleString("id-ID")}
                  </span>
                </div>
                
                <div className="mt-4 p-2 bg-info bg-opacity-10 rounded d-flex gap-2 align-items-start">
                  <FaInfoCircle className="text-info mt-1" />
                  <small className="text-muted">
                    Pembayaran diproses dengan aman melalui Midtrans Snap.
                  </small>
                </div>
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </Container>
    </div>
  );
};

export default Checkout;
