import React, { useState, useEffect, useContext } from "react";
import { Container, Row, Col, Card, Form, Button, Alert } from "react-bootstrap";
import { useLocation, useNavigate } from "react-router-dom";
import axios from "axios";
import { AuthContext } from "../../context/AuthContext";
import Loading from "../../components/loading/Loading";
import { FaCheckCircle, FaCreditCard, FaShoppingCart } from "react-icons/fa";
import "./Payment.css";

function Payment() {
  const location = useLocation();
  const navigate = useNavigate();
  const context = useContext(AuthContext);
  const userLogin = context.userLogin;
  const token = context.token;
  const daftarKursus = context.daftarKursus;

  const courseId = location.state?.courseId;

  const [kursus, setKursus] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isProcessing, setIsProcessing] = useState(false);
  const [statusBayar, setStatusBayar] = useState(null);
  const [nomorTrx, setNomorTrx] = useState("");

  const [namaKartu, setNamaKartu] = useState("");
  const [nomorKartu, setNomorKartu] = useState("");
  const [expDate, setExpDate] = useState("");
  const [cvv, setCvv] = useState("");

  function formatRp(angka) {
    if (!angka) return "Rp 0";
    return "Rp " + angka.toLocaleString("id-ID");
  }

  useEffect(() => {
    if (!courseId) {
      navigate("/courses");
      return;
    }

    let dataKursus = null;
    for (let i = 0; i < daftarKursus.length; i++) {
      if (daftarKursus[i].id === courseId) {
        dataKursus = daftarKursus[i];
        break;
      }
    }

    if (dataKursus) {
      setKursus(dataKursus);
    }
    
    setIsLoading(false);
  }, [courseId, navigate, daftarKursus]);

  async function handlePayment(e) {
    e.preventDefault();
    setIsProcessing(true);

    try {
      let respon = await axios.post("/api/orders", {
        productId: kursus.id,
        totalPrice: kursus.harga,
        paymentMethod: "Credit Card"
      }, {
        headers: { Authorization: "Bearer " + token }
      });

      if (respon.data.success) {
        setNomorTrx(respon.data.data.id);
        setStatusBayar("sukses");
        
        setTimeout(function() {
          navigate("/dashboard-user");
        }, 3000);
      } else {
        alert(respon.data.message || "Gagal melakukan pembayaran");
      }
    } catch (error) {
      console.log("Error bayar:", error);
      alert("Terjadi kesalahan saat memproses pembayaran");
    } finally {
      setIsProcessing(false);
    }
  }

  if (isLoading) return <Loading />;

  if (statusBayar === "sukses") {
    return (
      <Container className="d-flex justify-content-center align-items-center min-vh-100">
        <Card className="success-card text-center p-5">
          <Card.Body>
            <div className="success-icon mb-4">
              <FaCheckCircle color="#22c55e" />
            </div>
            <h2 className="mb-3">Pembayaran Berhasil!</h2>
            <p className="text-muted mb-4">
              Terima kasih. Transaksi Anda dengan nomor <strong>{nomorTrx}</strong> telah berhasil diproses.
            </p>
            <Alert variant="info">
              Mengarahkan ke Dashboard Anda dalam 3 detik...
            </Alert>
          </Card.Body>
        </Card>
      </Container>
    );
  }

  return (
    <div className="payment-page">
      <Container className="py-5">
        <h2 className="page-title mb-4">Pembayaran Kursus</h2>
        
        <Row>
          <Col lg={7} className="mb-4">
            <Card className="payment-card">
              <Card.Body className="p-4">
                <h4 className="section-title d-flex align-items-center gap-2 mb-4">
                  <FaCreditCard /> Detail Kartu
                </h4>
                
                <Form onSubmit={handlePayment}>
                  <Form.Group className="mb-3">
                    <Form.Label>Nama Pemegang Kartu</Form.Label>
                    <Form.Control 
                      type="text" 
                      placeholder="Contoh: John Doe" 
                      required
                      value={namaKartu}
                      onChange={(e) => setNamaKartu(e.target.value)}
                    />
                  </Form.Group>

                  <Form.Group className="mb-3">
                    <Form.Label>Nomor Kartu (16 Digit)</Form.Label>
                    <Form.Control 
                      type="text" 
                      placeholder="0000 0000 0000 0000" 
                      maxLength="16"
                      required
                      value={nomorKartu}
                      onChange={(e) => setNomorKartu(e.target.value)}
                    />
                  </Form.Group>

                  <Row>
                    <Col md={6}>
                      <Form.Group className="mb-4">
                        <Form.Label>Masa Berlaku (MM/YY)</Form.Label>
                        <Form.Control 
                          type="text" 
                          placeholder="MM/YY" 
                          required
                          value={expDate}
                          onChange={(e) => setExpDate(e.target.value)}
                        />
                      </Form.Group>
                    </Col>
                    <Col md={6}>
                      <Form.Group className="mb-4">
                        <Form.Label>CVV</Form.Label>
                        <Form.Control 
                          type="password" 
                          placeholder="123" 
                          maxLength="3"
                          required
                          value={cvv}
                          onChange={(e) => setCvv(e.target.value)}
                        />
                      </Form.Group>
                    </Col>
                  </Row>

                  <Button 
                    variant="primary" 
                    type="submit" 
                    className="w-100 btn-pay"
                    disabled={isProcessing}
                  >
                    {isProcessing ? "Memproses..." : `Bayar Sekarang - ${formatRp(kursus?.harga || 0)}`}
                  </Button>
                </Form>
              </Card.Body>
            </Card>
          </Col>

          <Col lg={5}>
            <Card className="summary-card">
              <Card.Body className="p-4">
                <h4 className="section-title d-flex align-items-center gap-2 mb-4">
                  <FaShoppingCart /> Ringkasan Pesanan
                </h4>
                
                {kursus && (
                  <>
                    <div className="d-flex mb-4 align-items-center">
                      <img src={kursus.thumbnail} alt="thumbnail" className="summary-img me-3" />
                      <div>
                        <h6 className="mb-1 fw-bold">{kursus.judul}</h6>
                        <small className="text-muted">Kategori: {kursus.kategori}</small>
                      </div>
                    </div>

                    <hr />

                    <div className="d-flex justify-content-between mb-2">
                      <span className="text-muted">Harga Kursus</span>
                      <span className="fw-bold">{formatRp(kursus.harga)}</span>
                    </div>
                    
                    <div className="d-flex justify-content-between mb-3">
                      <span className="text-muted">Biaya Admin</span>
                      <span className="fw-bold">Rp 0</span>
                    </div>

                    <hr />

                    <div className="d-flex justify-content-between mt-3">
                      <span className="fw-bold fs-5">Total</span>
                      <span className="fw-bold fs-5 text-primary">{formatRp(kursus.harga)}</span>
                    </div>
                  </>
                )}
              </Card.Body>
            </Card>
          </Col>
        </Row>
      </Container>
    </div>
  );
}

export default Payment;
