import React, { useCallback, useEffect, useState } from 'react';
import { ArrowLeft, Loader2, Lock, RefreshCw } from 'lucide-react';

const STORAGE_KEY = 'erza_admin_token';

export type OrderRow = {
  id: number;
  created_at: string;
  name: string;
  phone: string;
  address: string;
  size: string | null;
  quantity: string | null;
  model: string | null;
  delivery_area: string | null;
  total_amount: string | null;
};

export default function AdminDashboard() {
  const [token, setToken] = useState(() =>
    typeof window !== 'undefined' ? sessionStorage.getItem(STORAGE_KEY) ?? '' : '',
  );
  const [input, setInput] = useState('');
  const [orders, setOrders] = useState<OrderRow[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const fetchOrders = useCallback(async (auth: string) => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/admin/orders', {
        headers: { Authorization: `Bearer ${auth}` },
      });
      const data = await res.json().catch(() => ({}));
      if (res.status === 401) {
        sessionStorage.removeItem(STORAGE_KEY);
        setToken('');
        setOrders(null);
        setError('Invalid or expired token.');
        return;
      }
      if (!res.ok) {
        setError(typeof data.message === 'string' ? data.message : 'Could not load orders.');
        return;
      }
      if (Array.isArray(data.orders)) {
        setOrders(data.orders as OrderRow[]);
      } else {
        setError('Unexpected response.');
      }
    } catch {
      setError('Network error.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (token) {
      void fetchOrders(token);
    }
  }, [token, fetchOrders]);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    const t = input.trim();
    if (t.length < 16) {
      setError('Token must be at least 16 characters (same as ADMIN_TOKEN on the server).');
      return;
    }
    sessionStorage.setItem(STORAGE_KEY, t);
    setToken(t);
    setInput('');
  };

  const handleLogout = () => {
    sessionStorage.removeItem(STORAGE_KEY);
    setToken('');
    setOrders(null);
    setError('');
  };

  if (!token) {
    return (
      <div className="min-h-screen bg-zinc-950 text-zinc-100 flex items-center justify-center p-6 font-sans">
        <div className="w-full max-w-md border border-white/10 rounded-2xl bg-black/60 p-8 shadow-xl">
          <div className="flex items-center gap-3 text-[#D4AF37] mb-2">
            <Lock size={22} />
            <h1 className="text-xl font-bold tracking-tight">Admin</h1>
          </div>
          <p className="text-sm text-zinc-400 mb-6">
            Enter the server <code className="text-zinc-300">ADMIN_TOKEN</code> value. It is never
            stored in the app build — only in your server environment and here in the browser
            session until you close the tab.
          </p>
          <form onSubmit={handleLogin} className="space-y-4">
            <input
              type="password"
              autoComplete="off"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Admin token"
              className="w-full rounded-xl bg-zinc-900 border border-white/10 px-4 py-3 text-sm outline-none focus:border-[#D4AF37]/60"
            />
            {error ? <p className="text-sm text-red-400">{error}</p> : null}
            <button
              type="submit"
              className="w-full rounded-xl bg-gradient-to-r from-[#AA771C] to-[#D4AF37] text-black font-bold py-3 text-sm hover:opacity-95 active:scale-[0.99]"
            >
              Continue
            </button>
          </form>
          <a
            href="/"
            className="mt-6 flex items-center justify-center gap-2 text-sm text-zinc-500 hover:text-zinc-300"
          >
            <ArrowLeft size={16} /> Back to site
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 p-4 sm:p-8 font-sans">
      <div className="max-w-[1600px] mx-auto">
        <header className="flex flex-wrap items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-2xl font-black tracking-tight text-white">Orders</h1>
            <p className="text-sm text-zinc-500 mt-1">{orders?.length ?? 0} rows (newest first)</p>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <button
              type="button"
              disabled={loading}
              onClick={() => fetchOrders(token)}
              className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-zinc-900 px-4 py-2 text-sm font-semibold hover:bg-zinc-800 disabled:opacity-50"
            >
              {loading ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} />}
              Refresh
            </button>
            <button
              type="button"
              onClick={handleLogout}
              className="rounded-xl border border-red-500/30 bg-red-950/40 px-4 py-2 text-sm font-semibold text-red-200 hover:bg-red-950/60"
            >
              Log out
            </button>
            <a
              href="/"
              className="inline-flex items-center gap-2 rounded-xl border border-white/10 px-4 py-2 text-sm font-semibold text-zinc-300 hover:bg-white/5"
            >
              <ArrowLeft size={16} /> Site
            </a>
          </div>
        </header>

        {error ? (
          <div className="mb-4 rounded-xl border border-red-500/30 bg-red-950/30 px-4 py-3 text-sm text-red-200">
            {error}
          </div>
        ) : null}

        <div className="rounded-2xl border border-white/10 overflow-hidden bg-black/40">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm min-w-[900px]">
              <thead>
                <tr className="border-b border-white/10 bg-zinc-900/80 text-zinc-400 uppercase text-xs tracking-wider">
                  <th className="px-3 py-3 font-semibold">ID</th>
                  <th className="px-3 py-3 font-semibold whitespace-nowrap">Created</th>
                  <th className="px-3 py-3 font-semibold">Name</th>
                  <th className="px-3 py-3 font-semibold whitespace-nowrap">Phone</th>
                  <th className="px-3 py-3 font-semibold min-w-[180px]">Address</th>
                  <th className="px-3 py-3 font-semibold">Size</th>
                  <th className="px-3 py-3 font-semibold">Qty</th>
                  <th className="px-3 py-3 font-semibold min-w-[200px]">Model</th>
                  <th className="px-3 py-3 font-semibold">Delivery</th>
                  <th className="px-3 py-3 font-semibold whitespace-nowrap">Total</th>
                </tr>
              </thead>
              <tbody>
                {loading && !orders?.length ? (
                  <tr>
                    <td colSpan={10} className="px-6 py-16 text-center text-zinc-500">
                      <Loader2 className="inline animate-spin mr-2" size={20} />
                      Loading…
                    </td>
                  </tr>
                ) : orders && orders.length === 0 ? (
                  <tr>
                    <td colSpan={10} className="px-6 py-12 text-center text-zinc-500">
                      No orders yet.
                    </td>
                  </tr>
                ) : (
                  orders?.map((row) => (
                    <tr
                      key={row.id}
                      className="border-b border-white/5 hover:bg-white/[0.03] align-top"
                    >
                      <td className="px-3 py-3 text-zinc-500 whitespace-nowrap">{row.id}</td>
                      <td className="px-3 py-3 text-zinc-300 whitespace-nowrap text-xs">
                        {row.created_at
                          ? new Date(row.created_at).toLocaleString(undefined, {
                              dateStyle: 'short',
                              timeStyle: 'short',
                            })
                          : '—'}
                      </td>
                      <td className="px-3 py-3 font-medium text-white">{row.name}</td>
                      <td className="px-3 py-3 whitespace-nowrap">{row.phone}</td>
                      <td className="px-3 py-3 text-zinc-300 max-w-xs whitespace-pre-wrap break-words">
                        {row.address}
                      </td>
                      <td className="px-3 py-3 text-zinc-300">{row.size ?? '—'}</td>
                      <td className="px-3 py-3 text-zinc-300">{row.quantity ?? '—'}</td>
                      <td className="px-3 py-3 text-zinc-300 max-w-md whitespace-pre-wrap break-words">
                        {row.model ?? '—'}
                      </td>
                      <td className="px-3 py-3 text-zinc-300">{row.delivery_area ?? '—'}</td>
                      <td className="px-3 py-3 text-[#D4AF37] font-semibold whitespace-nowrap">
                        {row.total_amount ?? '—'}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
