"use client";

import { useState } from "react";

type Settings = { price: number; redirectUrl: string; popupTitle: string; popupDescription: string };
type Metric = { count: number; earn: number };
type Transaction = { orderId: string; phone: string; amount: number; currency: string; status: string; channel: string; reference: string; createdAt: string };
type Media = { id: string; filename: string; sort_order: number; url: string };

export function AdminDashboard(props: {
  email: string; signOutUrl: string; settings: Settings; today: Metric; yesterday: Metric;
  transactions: Transaction[]; media: Media[];
}) {
  const [settings, setSettings] = useState(props.settings);
  const [media, setMedia] = useState(props.media);
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const money = (value: number) => new Intl.NumberFormat("en-TZ", { maximumFractionDigits: 0 }).format(value);

  async function saveSettings(event: React.FormEvent) {
    event.preventDefault(); setBusy(true); setMessage("");
    const response = await fetch("/api/admin/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(settings) });
    const result = await response.json();
    setMessage(response.ok ? "Settings saved successfully." : result.message || "Could not save settings.");
    setBusy(false);
  }

  async function upload(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault(); setBusy(true); setMessage("");
    const form = new FormData(event.currentTarget);
    const response = await fetch("/api/admin/media", { method: "POST", body: form });
    const result = await response.json();
    if (response.ok) window.location.reload();
    else { setMessage(result.message || "Upload failed."); setBusy(false); }
  }

  async function persistOrder(next: Media[]) {
    setMedia(next);
    const response = await fetch("/api/admin/media", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids: next.map((item) => item.id) }) });
    if (!response.ok) setMessage("Could not save image order.");
  }

  function move(index: number, direction: -1 | 1) {
    const target = index + direction;
    if (target < 0 || target >= media.length) return;
    const next = [...media]; [next[index], next[target]] = [next[target], next[index]];
    void persistOrder(next);
  }

  async function remove(id: string) {
    if (!window.confirm("Delete this image?")) return;
    const response = await fetch("/api/admin/media", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id }) });
    if (response.ok) setMedia((items) => items.filter((item) => item.id !== id));
    else setMessage("Could not delete image.");
  }

  return (
    <main className="admin-shell">
      <aside className="admin-sidebar">
        <a className="brand admin-brand" href="/"><span className="brand-mark">L</span><span>PROJECT LOYD<small>CONTROL ROOM</small></span></a>
        <nav>
          <a href="#overview" className="active">Overview</a>
          <a href="#transactions">Transactions</a>
          <a href="#media">Media library</a>
          <a href="#settings">Settings</a>
        </nav>
        <div className="admin-user"><span>{props.email.slice(0, 1).toUpperCase()}</span><div><strong>Administrator</strong><small>{props.email}</small></div></div>
        <a className="signout" href={props.signOutUrl}>Sign out</a>
      </aside>

      <section className="admin-main">
        <header className="admin-top"><div><span className="admin-kicker">DASHBOARD</span><h1>Good to see you.</h1></div><a href="/" target="_blank">View customer page ↗</a></header>
        {message && <div className="admin-message">{message}</div>}

        <section id="overview" className="metric-grid">
          <article className="metric-card dark"><span>TODAY&apos;S EARN</span><strong><small>TSH</small>{money(props.today.earn)}</strong><p>{props.today.count} total transaction{props.today.count === 1 ? "" : "s"}</p></article>
          <article className="metric-card"><span>YESTERDAY&apos;S EARN</span><strong><small>TSH</small>{money(props.yesterday.earn)}</strong><p>{props.yesterday.count} total transaction{props.yesterday.count === 1 ? "" : "s"}</p></article>
          <article className="metric-card accent"><span>CURRENT PRICE</span><strong><small>TSH</small>{money(settings.price)}</strong><p>Customer checkout amount</p></article>
        </section>

        <section id="transactions" className="admin-panel">
          <div className="panel-heading"><div><span className="admin-kicker">ACTIVITY</span><h2>Last 20 transactions</h2></div><span className="live-label"><i /> LIVE RECORDS</span></div>
          <div className="table-wrap"><table><thead><tr><th>Order</th><th>Customer</th><th>Amount</th><th>Status</th><th>Channel</th><th>Date</th></tr></thead><tbody>
            {props.transactions.length ? props.transactions.map((transaction) => (
              <tr key={transaction.orderId}><td><strong>{transaction.orderId}</strong><small>{transaction.reference}</small></td><td>{transaction.phone}</td><td>TSH {money(transaction.amount)}</td><td><span className={`status ${transaction.status.toLowerCase()}`}>{transaction.status}</span></td><td>{transaction.channel}</td><td>{new Date(transaction.createdAt).toLocaleString("en-TZ", { dateStyle: "medium", timeStyle: "short", timeZone: "Africa/Dar_es_Salaam" })}</td></tr>
            )) : <tr><td colSpan={6} className="empty-row">No transactions yet.</td></tr>}
          </tbody></table></div>
        </section>

        <section id="media" className="admin-panel">
          <div className="panel-heading"><div><span className="admin-kicker">CONTENT</span><h2>Media library</h2></div><span>{media.length} image{media.length === 1 ? "" : "s"}</span></div>
          <form className="upload-box" onSubmit={upload}><input type="file" name="image" accept="image/*" required /><button disabled={busy}>{busy ? "Working…" : "Upload image"}</button><small>JPG, PNG, WebP or GIF · max 8 MB</small></form>
          <div className="media-admin-grid">{media.map((item, index) => (
            <article key={item.id}><img src={item.url} alt={item.filename} /><div><strong>{item.filename}</strong><span>Position {index + 1}</span></div><div className="media-controls"><button onClick={() => move(index, -1)} disabled={index === 0} aria-label="Move left">←</button><button onClick={() => move(index, 1)} disabled={index === media.length - 1} aria-label="Move right">→</button><button className="delete" onClick={() => void remove(item.id)}>Delete</button></div></article>
          ))}</div>
        </section>

        <section id="settings" className="admin-panel settings-panel">
          <div className="panel-heading"><div><span className="admin-kicker">CONFIGURATION</span><h2>Customer page settings</h2></div></div>
          <form onSubmit={saveSettings}>
            <label>Price (TSH)<input type="number" min="100" step="100" value={settings.price} onChange={(event) => setSettings({ ...settings, price: Number(event.target.value) })} required /></label>
            <label>Redirect link<input type="url" value={settings.redirectUrl} onChange={(event) => setSettings({ ...settings, redirectUrl: event.target.value })} required /></label>
            <label>Popup title<input value={settings.popupTitle} onChange={(event) => setSettings({ ...settings, popupTitle: event.target.value })} required /></label>
            <label className="full">Popup description<textarea rows={4} value={settings.popupDescription} onChange={(event) => setSettings({ ...settings, popupDescription: event.target.value })} required /></label>
            <button className="save-button" disabled={busy}>{busy ? "Saving…" : "Save all settings"}</button>
          </form>
        </section>
      </section>
    </main>
  );
}
