import { useState } from "react";

// ─── MOCK DATA ──────────────────────────────────────────────────────────────
const PICKUP_POINTS = [
  { id: 1, name: "City Bus Stand" },
  { id: 2, name: "Railway Station" },
  { id: 3, name: "Sector 12 Chowk" },
  { id: 4, name: "Gandhi Nagar Gate" },
  { id: 5, name: "MP Nagar Square" },
  { id: 6, name: "Arera Colony" },
];

const CURRENCY = "₹";

// ─── STYLES ────────────────────────────────────────────────────────────────
const css = `
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap');
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  .pp-root {
    font-family: 'Inter', sans-serif;
    background: #f0f4ff;
    color: #1e2a4a;
    min-height: 100vh;
    display: flex; flex-direction: column;
  }

  /* NAV */
  .pp-nav {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 28px; height: 60px;
    background: #1a56db;
    border-bottom: 1px solid #1648c4;
    position: sticky; top: 0; z-index: 50;
  }
  .pp-nav-brand { display: flex; align-items: center; gap: 10px; }
  .pp-nav-logo {
    width: 34px; height: 34px; border-radius: 8px;
    background: rgba(255,255,255,0.2);
    display: grid; place-items: center; font-size: 18px;
  }
  .pp-nav-name { font-size: 16px; font-weight: 700; color: #fff; }
  .pp-nav-name span { color: #bfdbfe; }
  .pp-nav-chip {
    font-size: 11px; color: #bfdbfe;
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.2);
    padding: 3px 10px; border-radius: 20px;
  }
  .pp-avatar {
    width: 32px; height: 32px; border-radius: 50%;
    background: rgba(255,255,255,0.25);
    display: grid; place-items: center;
    font-size: 13px; font-weight: 700; color: #fff; cursor: pointer;
  }

  /* LAYOUT */
  .pp-body { display: flex; flex: 1; }

  /* SIDEBAR */
  .pp-aside {
    width: 215px; flex-shrink: 0; background: #fff;
    border-right: 1px solid #e2e8f8;
    padding: 16px 10px; display: flex; flex-direction: column; gap: 2px;
  }
  .pp-aside-sec {
    font-size: 9.5px; letter-spacing: .14em; text-transform: uppercase;
    color: #94a3b8; padding: 12px 10px 5px;
  }
  .pp-aside-item {
    display: flex; align-items: center; gap: 9px;
    padding: 8px 11px; border-radius: 9px;
    font-size: 13px; color: #64748b; cursor: pointer; transition: all .15s;
  }
  .pp-aside-item:hover { background: #eff6ff; color: #1a56db; }
  .pp-aside-item.active { background: #dbeafe; color: #1a56db; font-weight: 600; }

  /* MAIN */
  .pp-main { flex: 1; padding: 28px 32px; }

  /* PAGE HEADER */
  .pp-page-header {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 24px;
  }
  .pp-page-title h1 { font-size: 22px; font-weight: 700; color: #1e2a4a; letter-spacing: -.3px; }
  .pp-page-title p { font-size: 13px; color: #64748b; margin-top: 3px; }

  /* ADD BTN */
  .pp-btn-add {
    display: flex; align-items: center; gap: 8px;
    padding: 10px 20px; border-radius: 9px;
    background: #1a56db; border: none; color: #fff;
    font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 600;
    cursor: pointer; transition: background .15s;
  }
  .pp-btn-add:hover { background: #1648c4; }

  /* CARD WRAPPER */
  .pp-card {
    background: #fff; border: 1px solid #e2e8f8;
    border-radius: 14px; overflow: hidden;
    box-shadow: 0 1px 6px rgba(26,86,219,0.04);
  }
  .pp-card-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 22px;
    border-bottom: 1px solid #f1f5fe;
    background: #fafcff;
  }
  .pp-card-title { font-size: 15px; font-weight: 600; color: #1e2a4a; display: flex; align-items: center; gap: 8px; }
  .pp-count-badge {
    font-size: 11px; font-weight: 600;
    background: #dbeafe; color: #1a56db;
    border: 1px solid #93c5fd;
    padding: 2px 9px; border-radius: 20px;
  }

  /* COL LABELS ROW */
  .pp-col-labels {
    display: grid;
    grid-template-columns: 2.2fr 1.2fr 1.2fr 1.2fr 44px;
    gap: 12px; padding: 10px 22px;
    border-bottom: 1px solid #f1f5fe;
    background: #f8faff;
  }
  .pp-col-label {
    font-size: 10.5px; text-transform: uppercase; letter-spacing: .1em;
    color: #94a3b8; font-weight: 600;
  }

  /* PICKUP ROW */
  .pp-row {
    display: grid;
    grid-template-columns: 2.2fr 1.2fr 1.2fr 1.2fr 44px;
    gap: 12px; padding: 14px 22px;
    align-items: end;
    border-bottom: 1px solid #f1f5fe;
    transition: background .15s;
    animation: fadeRow .2s ease;
  }
  .pp-row:last-child { border-bottom: none; }
  .pp-row:hover { background: #fafcff; }
  @keyframes fadeRow { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }

  /* INPUTS */
  .pp-label {
    font-size: 11px; text-transform: uppercase; letter-spacing: .09em;
    color: #64748b; font-weight: 500; margin-bottom: 5px;
    display: flex; align-items: center; gap: 4px;
  }
  .pp-req { color: #ef4444; font-size: 13px; line-height: 1; }

  .pp-select, .pp-input {
    width: 100%; background: #fff;
    border: 1px solid #cbd5e1;
    border-radius: 8px; padding: 9px 12px;
    color: #1e2a4a; font-family: 'Inter', sans-serif; font-size: 13.5px;
    outline: none; transition: border-color .15s, box-shadow .15s;
    appearance: none; -webkit-appearance: none;
  }
  .pp-select { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 10px center; padding-right: 30px; }
  .pp-select:focus, .pp-input:focus { border-color: #1a56db; box-shadow: 0 0 0 3px rgba(26,86,219,0.1); }
  .pp-select::placeholder, .pp-input::placeholder { color: #cbd5e1; }

  /* INPUT WITH ADDON */
  .pp-input-group { display: flex; border: 1px solid #cbd5e1; border-radius: 8px; overflow: hidden; transition: border-color .15s, box-shadow .15s; }
  .pp-input-group:focus-within { border-color: #1a56db; box-shadow: 0 0 0 3px rgba(26,86,219,0.1); }
  .pp-input-group .pp-input { border: none; border-radius: 0; box-shadow: none; }
  .pp-input-group .pp-input:focus { box-shadow: none; }
  .pp-addon {
    display: flex; align-items: center; padding: 0 12px;
    background: #f1f5f9; border-left: 1px solid #e2e8f0;
    font-size: 12px; color: #64748b; font-weight: 600; white-space: nowrap;
    font-family: 'DM Mono', monospace;
  }

  /* DELETE BTN */
  .pp-del-btn {
    width: 36px; height: 36px; border-radius: 8px;
    background: #fff1f2; border: 1px solid #fecdd3;
    color: #ef4444; cursor: pointer;
    display: grid; place-items: center; font-size: 15px;
    transition: all .15s; flex-shrink: 0; margin-top: 20px;
  }
  .pp-del-btn:hover { background: #ffe4e6; border-color: #fda4af; transform: scale(1.07); }

  /* EMPTY STATE */
  .pp-empty {
    padding: 48px 20px; text-align: center; color: #94a3b8;
  }
  .pp-empty-icon { font-size: 36px; margin-bottom: 10px; }
  .pp-empty p { font-size: 14px; }
  .pp-empty small { font-size: 12px; color: #cbd5e1; }

  /* FOOTER */
  .pp-footer {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 22px;
    background: #fafcff; border-top: 1px solid #e2e8f8;
  }
  .pp-footer-info { font-size: 13px; color: #64748b; }
  .pp-footer-info span { color: #1a56db; font-weight: 600; }
  .pp-btn-save {
    padding: 10px 28px; border-radius: 9px;
    background: #1a56db; border: none; color: #fff;
    font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 600;
    cursor: pointer; transition: background .15s;
  }
  .pp-btn-save:hover { background: #1648c4; }

  /* TOAST */
  .pp-toast {
    position: fixed; bottom: 24px; right: 24px;
    background: #fff; border: 1px solid #86efac;
    color: #166534; border-radius: 12px;
    padding: 13px 20px; font-size: 14px; font-weight: 500;
    display: flex; align-items: center; gap: 9px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.1);
    animation: slideUp .22s ease; z-index: 300;
  }
  @keyframes slideUp { from { transform: translateY(16px); opacity:0; } to { transform: none; opacity:1; } }

  @media (max-width: 860px) {
    .pp-aside { display: none; }
    .pp-main { padding: 16px; }
    .pp-col-labels { display: none; }
    .pp-row { grid-template-columns: 1fr; gap: 10px; }
    .pp-del-btn { margin-top: 0; width: 100%; }
  }
`;

// ─── PICKUP ROW COMPONENT ──────────────────────────────────────────────────
let idCounter = 3;

function PickupPoint({ row, onUpdate, onRemove, isOnly }) {
  const set = (k, v) => onUpdate({ ...row, [k]: v });
  return (
    <div className="pp-row">
      {/* Pickup Point */}
      <div>
        <div className="pp-label">
          Pickup Point <span className="pp-req">*</span>
        </div>
        <select
          className="pp-select"
          value={row.pickup_point_id}
          onChange={(e) => set("pickup_point_id", e.target.value)}
        >
          <option value="">— Select —</option>
          {PICKUP_POINTS.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </select>
      </div>

      {/* Distance */}
      <div>
        <div className="pp-label">Distance</div>
        <div className="pp-input-group">
          <input
            className="pp-input"
            type="number"
            min="0"
            step="0.1"
            placeholder="0.0"
            value={row.distance}
            onChange={(e) => set("distance", e.target.value)}
          />
          <div className="pp-addon">KM</div>
        </div>
      </div>

      {/* Pickup Time */}
      <div>
        <div className="pp-label">
          Pickup Time <span className="pp-req">*</span>
        </div>
        <div className="pp-input-group">
          <input
            className="pp-input"
            type="time"
            value={row.pickup_time}
            onChange={(e) => set("pickup_time", e.target.value)}
          />
          <div className="pp-addon">🕐</div>
        </div>
      </div>

      {/* Monthly Fees */}
      <div>
        <div className="pp-label">
          Monthly Fees <span className="pp-req">*</span>
        </div>
        <div className="pp-input-group">
          <div className="pp-addon">{CURRENCY}</div>
          <input
            className="pp-input"
            type="number"
            min="0"
            step="1"
            placeholder="0"
            value={row.fees}
            onChange={(e) => set("fees", e.target.value)}
          />
        </div>
      </div>

      {/* Delete */}
      <button
        className="pp-del-btn"
        title="Remove this pickup point"
        onClick={() => onRemove(row.id)}
        disabled={isOnly}
        style={isOnly ? { opacity: 0.3, cursor: "not-allowed" } : {}}
      >
        ✕
      </button>
    </div>
  );
}

export default function PickupPointManager() {
  const [rows, setRows] = useState([
    {
      id: 1,
      pickup_point_id: "1",
      distance: "5.2",
      pickup_time: "07:30",
      fees: "500",
    },
    {
      id: 2,
      pickup_point_id: "3",
      distance: "3.8",
      pickup_time: "07:45",
      fees: "400",
    },
  ]);
  const [toast, setToast] = useState("");

  const addRow = () => {
    idCounter += 1;
    setRows((p) => [
      ...p,
      {
        id: idCounter,
        pickup_point_id: "",
        distance: "",
        pickup_time: "",
        fees: "",
      },
    ]);
  };

  const updateRow = (updated) =>
    setRows((p) => p.map((r) => (r.id === updated.id ? updated : r)));

  const removeRow = (id) => setRows((p) => p.filter((r) => r.id !== id));

  const handleSave = () => {
    const invalid = rows.some(
      (r) => !r.pickup_point_id || !r.pickup_time || !r.fees,
    );
    if (invalid) {
      setToast("⚠️ Fill all required fields before saving");
      setTimeout(() => setToast(""), 2800);
      return;
    }
    setToast(`✓ ${rows.length} pickup point(s) saved successfully`);
    setTimeout(() => setToast(""), 2800);
  };

  return (
    <>
      <style>{css}</style>
      <div className="pp-root">
        git status {/* MAIN */}
        <main className="pp-main">
          {/* Page Header */}
          <div className="pp-page-header">
            <div className="pp-page-title">
              <h1>🚌 Pickup Point Manager</h1>
              <p>
                Add and manage transport pickup points, distance, time and
                monthly fees
              </p>
            </div>
            <button className="pp-btn-add" onClick={addRow}>
              ＋ Add Pickup Point
            </button>
          </div>

          {/* Main Card */}
          <div className="pp-card">
            {/* Card Header */}
            <div className="pp-card-header">
              <div className="pp-card-title">
                🗺️ Pickup Points
                <span className="pp-count-badge">
                  {rows.length} point{rows.length !== 1 ? "s" : ""}
                </span>
              </div>
              <div style={{ fontSize: 12, color: "#94a3b8" }}>
                <span style={{ color: "#ef4444" }}>*</span> required fields
              </div>
            </div>

            {/* Column Labels */}
            <div className="pp-col-labels">
              <div className="pp-col-label">Pickup Point *</div>
              <div className="pp-col-label">Distance</div>
              <div className="pp-col-label">Pickup Time *</div>
              <div className="pp-col-label">Monthly Fees ({CURRENCY}) *</div>
              <div className="pp-col-label"></div>
            </div>

            {/* Rows */}
            {rows.length === 0 ? (
              <div className="pp-empty">
                <div className="pp-empty-icon">🚏</div>
                <p>No pickup points added yet</p>
                <small>Click "Add Pickup Point" to get started</small>
              </div>
            ) : (
              rows.map((row) => (
                <PickupPoint
                  key={row.id}
                  row={row}
                  onUpdate={updateRow}
                  onRemove={removeRow}
                  isOnly={rows.length === 1}
                />
              ))
            )}

            {/* Footer */}
            <div className="pp-footer">
              <div className="pp-footer-info">
                Total: <span>{rows.length}</span> pickup point
                {rows.length !== 1 ? "s" : ""} configured
              </div>
              <button className="pp-btn-save" onClick={handleSave}>
                Save Changes
              </button>
            </div>
          </div>
        </main>
      </div>

      {/* TOAST */}
      {toast && <div className="pp-toast">{toast}</div>}
    </>
  );
}
