'use client';

import { useEffect, useState, useCallback } from 'react';
import { api, ApiError } from '@/lib/api';

type Listing = {
  id: number;
  title: string;
  city?: string;
  type?: string;
  pricing_unit?: string;
  base_price_minor?: number;
  is_verified?: boolean;
  is_active?: boolean;
  bookings_count?: number;
};

type Kind = 'venues' | 'resources';

const VENUE_TYPES = ['villa', 'farmhouse', 'hall', 'general'];
const VENUE_UNITS = ['per_night', 'per_day', 'per_slot'];
const RES_TYPES = ['event', 'equipment', 'space', 'service', 'other'];
const RES_UNITS = ['per_booking', 'per_hour', 'per_day', 'per_unit'];

const money = (minor?: number) => `PKR ${((minor ?? 0) / 100).toLocaleString()}`;

export default function ListingsPage() {
  const [kind, setKind] = useState<Kind>('venues');
  const [items, setItems] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editing, setEditing] = useState<Listing | null>(null);
  const [creating, setCreating] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await api.get<{ data: Listing[] }>(`/portal/${kind}`, true);
      setItems(res.data ?? []);
    } catch (e) {
      setError(e instanceof ApiError ? e.message : 'Could not load listings');
    } finally {
      setLoading(false);
    }
  }, [kind]);

  useEffect(() => {
    load();
  }, [load]);

  async function remove(id: number) {
    if (!confirm('Deactivate this listing?')) return;
    try {
      await api.del(`/portal/${kind}/${id}`, true);
      load();
    } catch (e) {
      alert(e instanceof ApiError ? e.message : 'Failed');
    }
  }

  return (
    <main className="mx-auto max-w-4xl px-4 py-8">
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold">My Listings</h1>
        <button
          onClick={() => { setCreating(true); setEditing(null); }}
          className="rounded-lg bg-brand-strong px-4 py-2 text-sm font-medium text-white hover:bg-brand-dark"
        >
          + New listing
        </button>
      </div>

      <div className="mb-6 flex gap-2">
        {(['venues', 'resources'] as Kind[]).map((k) => (
          <button
            key={k}
            onClick={() => setKind(k)}
            className={`rounded-full px-4 py-2 text-sm font-medium ${
              kind === k ? 'bg-brand-strong text-white' : 'bg-soft text-ink'
            }`}
          >
            {k === 'venues' ? 'Venues' : 'Resources'}
          </button>
        ))}
      </div>

      {error && <div className="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-700">{error}</div>}

      {loading ? (
        <p className="text-muted">Loading…</p>
      ) : items.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-hair p-10 text-center text-muted">
          No {kind} yet. Create your first listing.
        </div>
      ) : (
        <div className="space-y-3">
          {items.map((it) => (
            <div key={it.id} className="flex items-center justify-between rounded-xl border border-hair p-4">
              <div>
                <div className="flex items-center gap-2">
                  <span className="font-semibold">{it.title}</span>
                  {!it.is_verified && <span className="rounded bg-amber-100 px-2 py-0.5 text-xs text-amber-700">pending review</span>}
                  {!it.is_active && <span className="rounded bg-soft px-2 py-0.5 text-xs text-muted">inactive</span>}
                </div>
                <div className="mt-1 text-sm text-muted">
                  {it.type} · {it.city || '—'} · {money(it.base_price_minor)} {it.pricing_unit}
                  {typeof it.bookings_count === 'number' && ` · ${it.bookings_count} bookings`}
                </div>
              </div>
              <div className="flex gap-2">
                <button onClick={() => { setEditing(it); setCreating(false); }} className="rounded-lg border border-hair px-3 py-1.5 text-sm hover:bg-soft/50">Edit</button>
                <button onClick={() => remove(it.id)} className="rounded-lg border border-red-200 px-3 py-1.5 text-sm text-red-600 hover:bg-red-50">Deactivate</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {(creating || editing) && (
        <ListingForm
          kind={kind}
          listing={editing}
          onClose={() => { setCreating(false); setEditing(null); }}
          onSaved={() => { setCreating(false); setEditing(null); load(); }}
        />
      )}
    </main>
  );
}

function ListingForm({
  kind, listing, onClose, onSaved,
}: {
  kind: Kind; listing: Listing | null; onClose: () => void; onSaved: () => void;
}) {
  const isVenue = kind === 'venues';
  const types = isVenue ? VENUE_TYPES : RES_TYPES;
  const units = isVenue ? VENUE_UNITS : RES_UNITS;

  const [form, setForm] = useState<Record<string, string>>({
    title: listing?.title ?? '',
    type: listing?.type ?? types[0],
    city: listing?.city ?? '',
    pricing_unit: listing?.pricing_unit ?? units[0],
    base_price: listing ? String((listing.base_price_minor ?? 0) / 100) : '',
  });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const set = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));

  async function save() {
    setSaving(true);
    setErr(null);
    try {
      const body = {
        title: form.title,
        type: form.type,
        city: form.city,
        pricing_unit: form.pricing_unit,
        base_price_minor: Math.round(parseFloat(form.base_price || '0') * 100),
      };
      if (listing) await api.put(`/portal/${kind}/${listing.id}`, body, true);
      else await api.post(`/portal/${kind}`, body, true);
      onSaved();
    } catch (e) {
      setErr(e instanceof ApiError ? e.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/40 p-4 py-8 sm:items-center" onClick={onClose}>
      <div className="my-auto max-h-[90vh] w-full max-w-md overflow-y-auto rounded-2xl bg-white p-6" onClick={(e) => e.stopPropagation()}>
        <h2 className="mb-4 text-lg font-semibold">{listing ? 'Edit' : 'New'} {isVenue ? 'venue' : 'resource'}</h2>
        {err && <div className="mb-3 rounded-lg bg-red-50 p-2 text-sm text-red-700">{err}</div>}
        <div className="space-y-3">
          <Input label="Title" value={form.title} onChange={(v) => set('title', v)} />
          <div className="grid grid-cols-2 gap-3">
            <Select label="Type" value={form.type} options={types} onChange={(v) => set('type', v)} />
            <Input label="City" value={form.city} onChange={(v) => set('city', v)} />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Select label="Pricing unit" value={form.pricing_unit} options={units} onChange={(v) => set('pricing_unit', v)} />
            <Input label="Base price (PKR)" value={form.base_price} onChange={(v) => set('base_price', v)} />
          </div>
        </div>
        <div className="mt-5 flex gap-2">
          <button onClick={onClose} className="flex-1 rounded-lg border border-hair py-2 text-sm">Cancel</button>
          <button onClick={save} disabled={saving} className="flex-1 rounded-lg bg-brand-strong py-2 text-sm font-medium text-white disabled:opacity-50">
            {saving ? 'Saving…' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  );
}

function Input({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <div>
      <label className="mb-1 block text-sm font-medium text-ink">{label}</label>
      <input value={value} onChange={(e) => onChange(e.target.value)} className="w-full rounded-lg border border-hair px-3 py-2 outline-none focus:border-brand" />
    </div>
  );
}

function Select({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (v: string) => void }) {
  return (
    <div>
      <label className="mb-1 block text-sm font-medium text-ink">{label}</label>
      <select value={value} onChange={(e) => onChange(e.target.value)} className="w-full rounded-lg border border-hair px-3 py-2 outline-none focus:border-brand">
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>
  );
}
