import {
  useEffect,
  useState,
  useContext
} from "react"

import { AuthContext } from "../context/AuthContext"

const API_URL = "http://10.10.1.112:5000/telur"

const PRICE = {
  A: 1500,
  B: 1200,
  C: 900
}

export default function Dashboard() {

  const { user } = useContext(AuthContext)

  const [stock, setStock] = useState([])
  const [cart, setCart] = useState([])
  const [loading, setLoading] = useState(false)

  const [showQR, setShowQR] = useState(false)
  const [lastOrderId, setLastOrderId] = useState(null)
  const [file, setFile] = useState(null)

  // FETCH STOK
  const fetchData = async () => {

    try {

      const res = await fetch(API_URL)
      const data = await res.json()

      const map = {
        A: 0,
        B: 0,
        C: 0
      }

      data.forEach(row => {

        const g = row.grade

        if (map[g] !== undefined) {
          map[g]++
        }

      })

      setStock(
        Object.keys(map).map(g => ({
          grade: g,
          stok: map[g]
        }))
      )

    } catch (err) {

      console.log(err)

    }
  }

  useEffect(() => {
    fetchData()
  }, [])

  // GET QTY
  const getQty = (grade) => {
    return cart.find(c => c.grade === grade)?.qty || 0
  }

  // TAMBAH
  const increase = (grade) => {

    const itemStock =
      stock.find(s => s.grade === grade)?.stok || 0

    const currentQty = getQty(grade)

    if (currentQty >= itemStock) {
      alert("Stok tidak cukup")
      return
    }

    setCart(prev => {

      const found = prev.find(
        c => c.grade === grade
      )

      return found

        ? prev.map(c =>
            c.grade === grade
              ? {
                  ...c,
                  qty: c.qty + 1
                }
              : c
          )

        : [
            ...prev,
            {
              grade,
              qty: 1
            }
          ]
    })
  }

  // KURANG
  const decrease = (grade) => {

    setCart(prev => {

      const found =
        prev.find(c => c.grade === grade)

      if (!found) return prev

      if (found.qty <= 1) {
        return prev.filter(
          c => c.grade !== grade
        )
      }

      return prev.map(c =>

        c.grade === grade

          ? {
              ...c,
              qty: c.qty - 1
            }

          : c

      )
    })
  }

  // HAPUS
  const removeItem = (grade) => {

    setCart(prev =>
      prev.filter(c => c.grade !== grade)
    )
  }

  // TOTAL
  const total = cart.reduce((sum, item) => {

    return sum + (
      PRICE[item.grade] * item.qty
    )

  }, 0)

  // CHECKOUT
  const handleOrder = async () => {

    if (!cart.length) {
      return alert("Keranjang kosong")
    }

    setLoading(true)

    try {

      const res = await fetch(
        "http://10.10.1.112:5000/order",
        {
          method: "POST",

          headers: {
            "Content-Type": "application/json"
          },

          body: JSON.stringify({

            nama: user?.nama,

            cart: cart
          })
        }
      )

      const result = await res.json()

      if (result.success) {

        setLastOrderId(result.order_id)

        setShowQR(true)

      } else {

        alert(
          result.message || "Gagal order"
        )

      }

    } catch (err) {

      console.log(err)

      alert("Backend error")

    }

    setLoading(false)
  }

  // UPLOAD BUKTI
  const handleUpload = async () => {

    if (!file) {
      return alert("Pilih gambar dulu")
    }

    const formData = new FormData()

    formData.append("file", file)

    formData.append(
      "order_id",
      lastOrderId
    )

    try {

      const res = await fetch(
        "http://10.10.1.112:5000/upload-bukti",
        {
          method: "POST",
          body: formData
        }
      )

      const result = await res.json()

      if (result.success) {

        alert(
          "Bukti berhasil dikirim"
        )

        setShowQR(false)

        setCart([])

        fetchData()

      } else {

        alert("Upload gagal")

      }

    } catch (err) {

      console.log(err)

      alert("Server error")

    }
  }

  return (

    <div style={styles.page}>

      {/* HEADER */}

      <div style={styles.header}>

        <div>

          <h1 style={styles.title}>
            Sadewa Telur 🥚
          </h1>

          <p style={styles.subtitle}>
            Sistem penjualan telur premium
          </p>

        </div>

      </div>

      {/* STOK */}

      <h2 style={styles.sectionTitle}>
        Stok Telur
      </h2>

      <div style={styles.stockGrid}>

        {stock.map(item => {

          const qty =
            getQty(item.grade)

          return (

            <div
              key={item.grade}
              style={styles.stockCard}
            >

              <div style={styles.gradeBadge}>
                Grade {item.grade}
              </div>

              <h3 style={styles.stockNumber}>
                {item.stok}
              </h3>

              <p style={styles.stockLabel}>
                Stok tersedia
              </p>

              <div style={styles.price}>
                Rp {
                  PRICE[item.grade]
                    .toLocaleString()
                }
              </div>

              {qty === 0 ? (

                <button
                  onClick={() =>
                    increase(item.grade)
                  }
                  style={styles.addBtn}
                >
                  + Tambah
                </button>

              ) : (

                <div style={styles.qtyWrap}>

                  <button
                    onClick={() =>
                      decrease(item.grade)
                    }
                    style={styles.qtyBtn}
                  >
                    −
                  </button>

                  <span style={styles.qtyText}>
                    {qty}
                  </span>

                  <button
                    onClick={() =>
                      increase(item.grade)
                    }
                    style={styles.qtyBtn}
                  >
                    +
                  </button>

                </div>

              )}

            </div>

          )
        })}

      </div>

      {/* CART */}

      <div style={styles.cartBox}>

        <div style={styles.cartHeader}>

          <h2 style={styles.sectionTitle}>
            Keranjang
          </h2>

          <span style={styles.cartCount}>
            {cart.length} item
          </span>

        </div>

        {cart.length === 0 ? (

          <div style={styles.emptyCart}>
            Keranjang masih kosong
          </div>

        ) : (

          <>

            {cart.map(item => (

              <div
                key={item.grade}
                style={styles.cartItem}
              >

                <div>

                  <div style={styles.cartGrade}>
                    Grade {item.grade}
                  </div>

                  <div style={styles.cartPrice}>
                    Rp {
                      PRICE[item.grade]
                        .toLocaleString()
                    }
                  </div>

                </div>

                <div style={styles.cartRight}>

                  <span>
                    {item.qty}x
                  </span>

                  <button
                    onClick={() =>
                      removeItem(item.grade)
                    }
                    style={styles.removeBtn}
                  >
                    Hapus
                  </button>

                </div>

              </div>

            ))}

            <div style={styles.totalBox}>

              <span>Total</span>

              <span>
                Rp {total.toLocaleString()}
              </span>

            </div>

            <button
              onClick={handleOrder}
              disabled={loading}
              style={styles.checkoutBtn}
            >

              {
                loading
                  ? "Memproses..."
                  : "Pesan Sekarang"
              }

            </button>

          </>

        )}

      </div>

      {/* QR */}

      {showQR && (

        <div style={styles.qrBox}>

          <h2 style={styles.qrTitle}>
            Scan QR Pembayaran
          </h2>

          <img
            src="/qr.jpeg"
            alt="QR"
            style={styles.qrImage}
          />

          <div style={styles.qrTotal}>
            Total:
            {" "}
            Rp {total.toLocaleString()}
          </div>

          <input
            type="file"

            onChange={(e) =>
              setFile(e.target.files[0])
            }

            style={styles.fileInput}
          />

          <button
            onClick={handleUpload}
            style={styles.uploadBtn}
          >
            Upload Bukti Pembayaran
          </button>

        </div>

      )}

    </div>

  )
}

const styles = {

  page: {
    padding: 30,
  },

  header: {
    marginBottom: 30,
  },

  title: {
    fontSize: 48,
    margin: 0,
    color: "white",
  },

  subtitle: {
    color: "#94a3b8",
    marginTop: 8,
  },

  sectionTitle: {
    color: "white",
    marginBottom: 20,
  },

  stockGrid: {
    display: "grid",

    gridTemplateColumns:
      "repeat(auto-fit, minmax(240px, 1fr))",

    gap: 20,

    marginBottom: 35,
  },

  stockCard: {

    background:
      "rgba(15,23,42,0.82)",

    border:
      "1px solid rgba(255,255,255,0.08)",

    borderRadius: 22,

    padding: 24,

    backdropFilter: "blur(12px)",

    boxShadow:
      "0 10px 30px rgba(0,0,0,0.35)",
  },

  gradeBadge: {

    display: "inline-block",

    padding: "6px 12px",

    borderRadius: 999,

    background:
      "rgba(245,158,11,0.15)",

    color: "#fbbf24",

    fontSize: 13,

    marginBottom: 16,
  },

  stockNumber: {
    fontSize: 42,
    margin: 0,
    color: "white",
  },

  stockLabel: {
    color: "#94a3b8",
    marginTop: 6,
  },

  price: {
    marginTop: 16,
    marginBottom: 18,
    color: "#f97316",
    fontWeight: 700,
    fontSize: 18,
  },

  addBtn: {

    width: "100%",

    border: "none",

    padding: "12px",

    borderRadius: 14,

    background:
      "linear-gradient(135deg, #f59e0b, #ea580c)",

    color: "white",

    fontWeight: 700,

    cursor: "pointer",
  },

  qtyWrap: {

    display: "flex",

    alignItems: "center",

    justifyContent: "center",

    gap: 14,
  },

  qtyBtn: {

    width: 40,

    height: 40,

    borderRadius: 12,

    border: "none",

    background:
      "rgba(255,255,255,0.08)",

    color: "white",

    fontSize: 20,

    cursor: "pointer",
  },

  qtyText: {
    color: "white",
    fontWeight: 700,
    fontSize: 18,
  },

  cartBox: {

    background:
      "rgba(15,23,42,0.82)",

    border:
      "1px solid rgba(255,255,255,0.08)",

    borderRadius: 24,

    padding: 24,

    backdropFilter: "blur(12px)",

    boxShadow:
      "0 10px 30px rgba(0,0,0,0.35)",
  },

  cartHeader: {

    display: "flex",

    justifyContent: "space-between",

    alignItems: "center",

    marginBottom: 20,
  },

  cartCount: {
    color: "#94a3b8",
  },

  emptyCart: {
    color: "#94a3b8",
  },

  cartItem: {

    display: "flex",

    justifyContent: "space-between",

    alignItems: "center",

    padding: "14px 0",

    borderBottom:
      "1px solid rgba(255,255,255,0.05)",
  },

  cartGrade: {
    color: "white",
    fontWeight: 700,
  },

  cartPrice: {
    color: "#94a3b8",
    marginTop: 4,
  },

  cartRight: {

    display: "flex",

    alignItems: "center",

    gap: 12,

    color: "white",
  },

  removeBtn: {

    border: "none",

    background:
      "rgba(239,68,68,0.15)",

    color: "#f87171",

    padding: "8px 12px",

    borderRadius: 10,

    cursor: "pointer",
  },

  totalBox: {

    display: "flex",

    justifyContent: "space-between",

    marginTop: 24,

    color: "white",

    fontWeight: 700,

    fontSize: 20,
  },

  checkoutBtn: {

    width: "100%",

    marginTop: 20,

    border: "none",

    padding: "14px",

    borderRadius: 16,

    background:
      "linear-gradient(135deg, #f59e0b, #ea580c)",

    color: "white",

    fontWeight: 700,

    fontSize: 15,

    cursor: "pointer",

    boxShadow:
      "0 10px 25px rgba(245,158,11,0.25)",
  },

  qrBox: {

    marginTop: 30,

    background:
      "rgba(15,23,42,0.82)",

    border:
      "1px solid rgba(255,255,255,0.08)",

    borderRadius: 24,

    padding: 30,

    textAlign: "center",
  },

  qrTitle: {
    color: "white",
    marginBottom: 20,
  },

  qrImage: {
    width: 220,
    borderRadius: 16,
  },

  qrTotal: {
    color: "#fbbf24",
    fontWeight: 700,
    marginTop: 20,
    marginBottom: 20,
  },

  fileInput: {
    color: "white",
    marginBottom: 20,
  },

  uploadBtn: {

    border: "none",

    padding: "14px 20px",

    borderRadius: 14,

    background:
      "linear-gradient(135deg, #22c55e, #16a34a)",

    color: "white",

    fontWeight: 700,

    cursor: "pointer",
  },
}