import { useEffect, useState } from "react"

const API = "http://10.10.1.112:5000"

const FILTERS = [
  { label: "Semua", value: "semua" },
  { label: "Menunggu verifikasi", value: "menunggu_verifikasi" },
  { label: "Disetujui", value: "disetujui" },
  { label: "Ditolak", value: "ditolak" },
]

const STATUS_CONFIG = {
  menunggu_verifikasi: {
    label: "Menunggu",
    dot: "#f59e0b",
    bg: "rgba(245,158,11,0.15)",
    color: "#fbbf24",
  },

  disetujui: {
    label: "Disetujui",
    dot: "#22c55e",
    bg: "rgba(34,197,94,0.15)",
    color: "#4ade80",
  },

  ditolak: {
    label: "Ditolak",
    dot: "#ef4444",
    bg: "rgba(239,68,68,0.15)",
    color: "#f87171",
  },
}

export default function AdminDashboard() {

  const [orders, setOrders] = useState([])
  const [filter, setFilter] = useState("semua")
  const [loading, setLoading] = useState(false)

  const fetchOrders = async () => {

    setLoading(true)

    try {

      const res = await fetch(`${API}/orders`)
      const data = await res.json()

      setOrders(data)

    } catch (err) {

      console.error(err)

    } finally {

      setLoading(false)

    }
  }

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

  const updateStatus = async (id, status) => {

    try {

      await fetch(`${API}/order/status`, {
        method: "POST",

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

        body: JSON.stringify({
          order_id: id,
          status
        }),
      })

      fetchOrders()

    } catch (err) {

      console.error(err)

      alert("Gagal memperbarui status.")

    }
  }

  const filtered = filter === "semua"
    ? orders
    : orders.filter(o => o.status === filter)

  return (
    <div style={styles.page}>

      {/* HEADER */}
      <div style={styles.header}>

        <div style={styles.headerIcon}>
          🥚
        </div>

        <div>

          <h1 style={styles.h1}>
            Admin Dashboard
          </h1>

          <p style={styles.subtitle}>
            Verifikasi pembayaran penjualan telur
          </p>

        </div>

      </div>

      {/* STATS */}
      <div style={styles.statsGrid}>

        <div style={styles.statCard}>

          <div style={styles.statTitle}>
            Total Pesanan
          </div>

          <div style={styles.statValue}>
            {orders.length}
          </div>

        </div>

        <div style={styles.statCard}>

          <div style={styles.statTitle}>
            Menunggu
          </div>

          <div style={styles.statValue}>
            {
              orders.filter(
                o => o.status === "menunggu_verifikasi"
              ).length
            }
          </div>

        </div>

        <div style={styles.statCard}>

          <div style={styles.statTitle}>
            Disetujui
          </div>

          <div style={styles.statValue}>
            {
              orders.filter(
                o => o.status === "disetujui"
              ).length
            }
          </div>

        </div>

      </div>

      {/* FILTER */}
      <div style={styles.filterBar}>

        {FILTERS.map(f => (

          <button
            key={f.value}
            onClick={() => setFilter(f.value)}
            style={{
              ...styles.filterBtn,

              ...(filter === f.value
                ? styles.filterBtnActive
                : {})
            }}
          >
            {f.label}
          </button>

        ))}

        <button
          onClick={fetchOrders}
          style={{
            ...styles.filterBtn,
            marginLeft: "auto"
          }}
        >
          ↻ Refresh
        </button>

      </div>

      {/* TABLE */}
      <div style={styles.tableWrap}>

        {loading ? (

          <div style={styles.empty}>
            Memuat data...
          </div>

        ) : filtered.length === 0 ? (

          <div style={styles.empty}>
            Tidak ada pesanan.
          </div>

        ) : (

          <table style={styles.table}>

            <thead>

              <tr>

                {
                  [
                    "ID",
                    "Nama",
                    "Total",
                    "Status",
                    "Bukti",
                    "Aksi"
                  ].map(h => (

                    <th
                      key={h}
                      style={styles.th}
                    >
                      {h}
                    </th>

                  ))
                }

              </tr>

            </thead>

            <tbody>

              {filtered.map(order => {

                const cfg =
                  STATUS_CONFIG[order.status]

                return (

                  <tr
                    key={order.id}
                    style={styles.row}
                  >

                    <td
                      style={{
                        ...styles.td,
                        ...styles.idCell
                      }}
                    >
                      #{order.id}
                    </td>

                    <td
                      style={{
                        ...styles.td,
                        fontWeight: 600
                      }}
                    >
                      {order.nama || "—"}
                    </td>

                    <td
                      style={{
                        ...styles.td,
                        fontWeight: 600
                      }}
                    >
                      Rp {
                        (order.total || 0)
                          .toLocaleString("id-ID")
                      }
                    </td>

                    <td style={styles.td}>

                      {cfg ? (

                        <span
                          style={{
                            ...styles.badge,
                            background: cfg.bg,
                            color: cfg.color
                          }}
                        >

                          <span
                            style={{
                              ...styles.dot,
                              background: cfg.dot
                            }}
                          />

                          {cfg.label}

                        </span>

                      ) : (

                        <span style={styles.badge}>
                          {order.status}
                        </span>

                      )}

                    </td>

                    <td style={styles.td}>

                      {order.bukti_pembayaran ? (

                        <a
                          href={`${API}/uploads-bukti/${order.bukti_pembayaran}`}
                          target="_blank"
                          rel="noreferrer"
                          style={styles.link}
                        >
                          📄 Lihat
                        </a>

                      ) : (

                        <span style={styles.noData}>
                          —
                        </span>

                      )}

                    </td>

                    <td style={styles.td}>

                      {
                        order.status === "menunggu_verifikasi"

                          ? (

                            <div style={styles.actionWrap}>

                              <button
                                onClick={() =>
                                  updateStatus(
                                    order.id,
                                    "disetujui"
                                  )
                                }
                                style={styles.btnApprove}
                              >
                                ✓ Setujui
                              </button>

                              <button
                                onClick={() =>
                                  updateStatus(
                                    order.id,
                                    "ditolak"
                                  )
                                }
                                style={styles.btnReject}
                              >
                                ✕ Tolak
                              </button>

                            </div>

                          )

                          : (
                            <span style={styles.noData}>
                              —
                            </span>
                          )
                      }

                    </td>

                  </tr>

                )
              })}

            </tbody>

          </table>

        )}

      </div>

    </div>
  )
}

const styles = {

  page: {
    padding: "2rem",
    fontFamily: "Inter, sans-serif",
    maxWidth: 1200,
    margin: "0 auto",
    minHeight: "100vh",
  },

  header: {
    display: "flex",
    alignItems: "center",
    gap: 14,
    marginBottom: 30,
  },

  headerIcon: {
    width: 52,
    height: 52,

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

    borderRadius: 16,

    display: "flex",
    alignItems: "center",
    justifyContent: "center",

    fontSize: 24,

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

  h1: {
    fontSize: 34,
    fontWeight: 700,
    margin: 0,
    color: "#ffffff",
  },

  subtitle: {
    fontSize: 14,
    color: "#94a3b8",
    marginTop: 4,
  },

  statsGrid: {
    display: "grid",

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

    gap: 18,

    marginBottom: 30,
  },

  statCard: {

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

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

    borderRadius: 20,

    padding: 24,

    backdropFilter: "blur(10px)",

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

  statTitle: {
    color: "#94a3b8",
    fontSize: 14,
    marginBottom: 10,
  },

  statValue: {
    color: "white",
    fontSize: 36,
    fontWeight: 700,
  },

  filterBar: {
    display: "flex",
    gap: 10,
    flexWrap: "wrap",
    marginBottom: 20,
    alignItems: "center",
  },

  filterBtn: {

    padding: "8px 16px",

    borderRadius: 999,

    fontSize: 13,

    cursor: "pointer",

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

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

    color: "#cbd5e1",

    backdropFilter: "blur(10px)",

    transition: "0.2s",
  },

  filterBtnActive: {

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

    color: "white",

    borderColor: "transparent",

    fontWeight: 600,

    boxShadow:
      "0 8px 20px rgba(245,158,11,0.25)",
  },

  tableWrap: {

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

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

    borderRadius: 20,

    overflow: "hidden",

    backdropFilter: "blur(12px)",

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

  table: {
    width: "100%",
    borderCollapse: "collapse",
    fontSize: 14,
  },

  th: {

    fontSize: 12,

    fontWeight: 600,

    color: "#94a3b8",

    textAlign: "left",

    padding: "14px",

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

    background: "#111827",
  },

  td: {

    padding: "14px",

    borderBottom:
      "1px solid rgba(255,255,255,0.04)",

    color: "#f8fafc",

    verticalAlign: "middle",
  },

  row: {
    transition: "0.2s",
  },

  idCell: {
    fontFamily: "monospace",
    fontSize: 12,
    color: "#94a3b8",
  },

  badge: {

    display: "inline-flex",

    alignItems: "center",

    gap: 6,

    padding: "6px 12px",

    borderRadius: 999,

    fontSize: 12,

    fontWeight: 600,
  },

  dot: {
    width: 6,
    height: 6,
    borderRadius: "50%",
  },

  link: {
    color: "#60a5fa",
    fontSize: 13,
  },

  actionWrap: {
    display: "flex",
    gap: 8,
  },

  btnApprove: {

    background:
      "rgba(34,197,94,0.15)",

    color: "#4ade80",

    border:
      "1px solid rgba(34,197,94,0.25)",

    padding: "7px 14px",

    borderRadius: 10,

    fontSize: 13,

    cursor: "pointer",
  },

  btnReject: {

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

    color: "#f87171",

    border:
      "1px solid rgba(239,68,68,0.25)",

    padding: "7px 14px",

    borderRadius: 10,

    fontSize: 13,

    cursor: "pointer",
  },

  noData: {
    color: "#94a3b8",
    fontSize: 13,
  },

  empty: {
    textAlign: "center",
    padding: "3rem",
    color: "#94a3b8",
    fontSize: 14,
  },
}