import { createResource, createSignal, createMemo, Show, For } from 'solid-js';

const API = '/api/gateway';

type Review = {
  id: string;
  reviewer_name?: string;
  reviewer_id?: string;
  subject_type?: string;
  rating?: number;
  title?: string;
  status: 'PUBLISHED' | 'HIDDEN' | string;
};

async function loadReviews(): Promise<Review[]> {
  try {
    const res = await fetch(`${API}/api/admin/reviews`);
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.reviews || []);
  } catch {
    return [];
  }
}

function typeBadgeStyle(subjectType: string): string {
  switch ((subjectType || '').toUpperCase()) {
    case 'PLATFORM':
      return 'background:#dbeafe;color:#1d4ed8;border-color:#bfdbfe';
    case 'PACKAGE':
      return 'background:#dcfce7;color:#166534;border-color:#bbf7d0';
    case 'SUPPORT':
      return 'background:#fff7ed;color:#c2410c;border-color:#fed7aa';
    default:
      return 'background:#f1f5f9;color:#475569;border-color:#e2e8f0';
  }
}

const defaultForm = () => ({
  subject_type: 'PLATFORM',
  subject_id: 'general',
  reviewer_name: '',
  rating: 5,
  title: '',
  comment: '',
});

export default function ReviewPage() {
  const [reviews, { refetch }] = createResource(loadReviews);
  const [activeTab, setActiveTab] = createSignal<'list' | 'create'>('list');
  const [search, setSearch] = createSignal('');
  const [form, setForm] = createSignal(defaultForm());
  const [saving, setSaving] = createSignal(false);
  const [toggling, setToggling] = createSignal('');
  const [formError, setFormError] = createSignal('');

  const filteredReviews = createMemo(() => {
    const q = search().toLowerCase();
    const all = reviews() ?? [];
    if (!q) return all;
    return all.filter((r) =>
      (r.reviewer_name || r.reviewer_id || '').toLowerCase().includes(q) ||
      (r.title || '').toLowerCase().includes(q) ||
      (r.subject_type || '').toLowerCase().includes(q) ||
      (r.status || '').toLowerCase().includes(q)
    );
  });

  const resetForm = () => {
    setForm(defaultForm());
    setFormError('');
  };

  const handleSave = async (e: Event) => {
    e.preventDefault();
    try {
      setSaving(true);
      setFormError('');
      const f = form();
      const res = await fetch(`${API}/api/admin/reviews`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          subject_type: f.subject_type,
          subject_id: f.subject_id,
          reviewer_name: f.reviewer_name,
          rating: Number(f.rating),
          title: f.title,
          comment: f.comment,
        }),
      });
      if (!res.ok) throw new Error('Failed to create review');
      resetForm();
      refetch();
      setActiveTab('list');
    } catch (err: unknown) {
      setFormError(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  };

  const handleUpdateStatus = async (review: Review, status: 'PUBLISHED' | 'HIDDEN') => {
    try {
      setToggling(review.id);
      const res = await fetch(`${API}/api/admin/reviews/${review.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      });
      if (!res.ok) throw new Error('Failed to update');
      refetch();
    } catch {
      // ignore
    } finally {
      setToggling('');
    }
  };

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <h1 class="text-xl font-semibold text-gray-900">Review Management</h1>
          <p class="text-sm text-gray-500 mt-0.5">Moderate platform reviews</p>
        </div>

        {/* Tabs */}
        <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
          <button
            type="button"
            class={activeTab() === 'list'
              ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
              : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => setActiveTab('list')}
          >
            Reviews
          </button>
          <button
            type="button"
            class={activeTab() === 'create'
              ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
              : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
            onClick={() => { resetForm(); setActiveTab('create'); }}
          >
            Create Review
          </button>
        </div>

        <div class="flex-1 p-6">
          <Show when={activeTab() === 'list'}>
            <div style="margin-bottom:16px">
              <input
                type="text"
                placeholder="Search by reviewer, title, type, or status..."
                value={search()}
                onInput={(e) => setSearch(e.currentTarget.value)}
                style="padding:8px 12px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;min-width:320px"
              />
            </div>
            <div class="table-card">
              <div class="overflow-x-auto">
                <table class="data-table w-full text-sm">
                  <thead>
                    <tr>
                      <th>Reviewer</th>
                      <th>Type</th>
                      <th>Rating</th>
                      <th>Title</th>
                      <th>Status</th>
                      <th class="text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <Show when={reviews.loading}>
                      <tr><td colspan="6" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                    </Show>
                    <Show when={!reviews.loading && reviews.error}>
                      <tr><td colspan="6" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
                    </Show>
                    <Show when={!reviews.loading && !reviews.error && filteredReviews().length === 0}>
                      <tr><td colspan="6" style="text-align:center;padding:32px;color:#94a3b8">No reviews found.</td></tr>
                    </Show>
                    <Show when={!reviews.loading && !reviews.error && filteredReviews().length > 0}>
                      <For each={filteredReviews()}>
                        {(item) => {
                          const subjectType = item.subject_type || '—';
                          const isPublished = item.status === 'PUBLISHED';
                          return (
                            <tr class="hover:bg-slate-50">
                              <td class="font-semibold text-slate-900">{item.reviewer_name || item.reviewer_id || '—'}</td>
                              <td>
                                <span style={`${typeBadgeStyle(subjectType)};padding:2px 10px;border-radius:999px;font-size:12px;font-weight:600;border:1px solid;display:inline-block`}>
                                  {subjectType}
                                </span>
                              </td>
                              <td class="text-slate-500">
                                {item.rating != null ? `⭐ ${item.rating}` : '—'}
                              </td>
                              <td class="text-slate-500">{item.title || '—'}</td>
                              <td>
                                <span class={`inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600 ${isPublished ? 'active' : ''}`}
                                  style={isPublished ? '' : 'background:#f1f5f9;color:#475569;border-color:#e2e8f0'}
                                >
                                  {isPublished ? 'Published' : 'Hidden'}
                                </span>
                              </td>
                              <td>
                                <div class="flex items-center justify-end gap-1">
                                  <Show when={isPublished}>
                                    <button
                                      class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                      disabled={toggling() === item.id}
                                      onClick={() => handleUpdateStatus(item, 'HIDDEN')}
                                    >
                                      {toggling() === item.id ? '...' : 'Hide'}
                                    </button>
                                  </Show>
                                  <Show when={!isPublished}>
                                    <button
                                      class="btn-primary"
                                      disabled={toggling() === item.id}
                                      onClick={() => handleUpdateStatus(item, 'PUBLISHED')}
                                    >
                                      {toggling() === item.id ? '...' : 'Publish'}
                                    </button>
                                  </Show>
                                </div>
                              </td>
                            </tr>
                          );
                        }}
                      </For>
                    </Show>
                  </tbody>
                </table>
              </div>
            </div>
          </Show>

          <Show when={activeTab() === 'create'}>
            <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:520px">
              <h2 style="margin:0 0 20px;font-size:16px;font-weight:700">Create Review</h2>
              <Show when={formError()}>
                <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-bottom:12px">{formError()}</div>
              </Show>
              <form onSubmit={handleSave} style="display:flex;flex-direction:column;gap:14px">
                <div class="field">
                  <label>Subject Type</label>
                  <select
                    value={form().subject_type}
                    onChange={(e) => setForm({ ...form(), subject_type: e.currentTarget.value })}
                  >
                    <option value="PLATFORM">PLATFORM</option>
                    <option value="PACKAGE">PACKAGE</option>
                    <option value="SUPPORT">SUPPORT</option>
                  </select>
                </div>
                <div class="field">
                  <label>Subject ID</label>
                  <input
                    type="text"
                    value={form().subject_id}
                    onInput={(e) => setForm({ ...form(), subject_id: e.currentTarget.value })}
                    placeholder="e.g. general or package UUID"
                  />
                </div>
                <div class="field">
                  <label>Reviewer Name</label>
                  <input
                    type="text"
                    value={form().reviewer_name}
                    onInput={(e) => setForm({ ...form(), reviewer_name: e.currentTarget.value })}
                    required
                    placeholder="Full name"
                  />
                </div>
                <div class="field">
                  <label>Rating</label>
                  <select
                    value={form().rating}
                    onChange={(e) => setForm({ ...form(), rating: Number(e.currentTarget.value) })}
                  >
                    <option value={5}>5 — Excellent</option>
                    <option value={4}>4 — Good</option>
                    <option value={3}>3 — Average</option>
                    <option value={2}>2 — Poor</option>
                    <option value={1}>1 — Terrible</option>
                  </select>
                </div>
                <div class="field">
                  <label>Title</label>
                  <input
                    type="text"
                    value={form().title}
                    onInput={(e) => setForm({ ...form(), title: e.currentTarget.value })}
                    required
                    placeholder="Review title"
                  />
                </div>
                <div class="field">
                  <label>Comment</label>
                  <textarea
                    value={form().comment}
                    onInput={(e) => setForm({ ...form(), comment: e.currentTarget.value })}
                    rows={4}
                    placeholder="Detailed review..."
                    style="resize:vertical"
                  />
                </div>
                <div class="actions">
                  <button class="btn-primary" type="submit" disabled={saving()}>
                    {saving() ? 'Saving...' : 'Save Review'}
                  </button>
                </div>
              </form>
            </section>
          </Show>
        </div>
      </div>
  );
}
