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

const API = '';

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 [statusFilter, setStatusFilter] = createSignal<'all' | 'published' | 'hidden'>('all');
  const [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'rating_desc' | 'rating_asc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);
  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();
    let data = reviews() ?? [];
    if (q) {
      data = data.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)
      );
    }
    if (statusFilter() !== 'all') {
      data = data.filter((r) => {
        const published = String(r.status || '').toUpperCase() === 'PUBLISHED';
        return statusFilter() === 'published' ? published : !published;
      });
    }
    const sorted = [...data];
    sorted.sort((a, b) => {
      const aRating = Number(a.rating ?? 0);
      const bRating = Number(b.rating ?? 0);
      if (sortBy() === 'oldest') return String(a.id || '').localeCompare(String(b.id || ''));
      if (sortBy() === 'rating_desc') return bRating - aRating;
      if (sortBy() === 'rating_asc') return aRating - bRating;
      return String(b.id || '').localeCompare(String(a.id || ''));
    });
    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Reviewer', 'Type', 'Rating', 'Title', 'Status'];
    const rows = filteredReviews().map((item) => [
      item.reviewer_name || item.reviewer_id || '—',
      item.subject_type || '—',
      item.rating != null ? String(item.rating) : '—',
      item.title || '—',
      item.status || '—',
    ]);
    const csv = [headers, ...rows].map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'review-management.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  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="w-full space-y-6 pb-8">
        <div style="margin-bottom:1.5rem">
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Review Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">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>
          <Show when={activeTab() === 'list'}>
            <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
            <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;position:relative;z-index:20;margin-bottom:0">
              <input
                type="text"
                placeholder="Search by reviewer, title, type, or status..."
                value={search()}
                onInput={(e) => setSearch(e.currentTarget.value)}
                style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
              />
              <div style="position:relative;">
                <button type="button" onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                  Sort
                </button>
                <Show when={sortMenuOpen()}>
                  <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                    <For each={[
                      { key: 'newest', label: 'Newest First' },
                      { key: 'oldest', label: 'Oldest First' },
                      { key: 'rating_desc', label: 'Rating High-Low' },
                      { key: 'rating_asc', label: 'Rating Low-High' },
                    ] as { key: 'newest' | 'oldest' | 'rating_desc' | 'rating_asc'; label: string }[]}>
                      {(item) => (
                        <button type="button" onClick={() => { setSortBy(item.key); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === item.key ? '#FF5E13' : '#374151'};background:${sortBy() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                      )}
                    </For>
                  </div>
                </Show>
              </div>
              <div style="position:relative;">
                <button type="button" onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                  Filters
                </button>
                <Show when={filterMenuOpen()}>
                  <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                    <For each={[
                      { key: 'all', label: 'All Status' },
                      { key: 'published', label: 'Published' },
                      { key: 'hidden', label: 'Hidden' },
                    ] as { key: 'all' | 'published' | 'hidden'; label: string }[]}>
                      {(item) => (
                        <button type="button" onClick={() => { setStatusFilter(item.key); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === item.key ? '#FF5E13' : '#374151'};background:${statusFilter() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                      )}
                    </For>
                  </div>
                </Show>
              </div>
              <button type="button" onClick={exportCsv} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Export
              </button>
            </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>
              <Show when={!reviews.loading && !reviews.error && filteredReviews().length > 0}>
                <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px">
                  <p style="font-size:13px;color:#6B7280">
                    Showing <strong style="font-weight:600;color:#111827">1–{filteredReviews().length}</strong> of <strong style="font-weight:600;color:#111827">{filteredReviews().length}</strong> reviews
                  </p>
                  <div style="display:flex;align-items:center;gap:4px">
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">‹</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;background:#FF5E13;color:white;font-size:13px;font-weight:600;border:none;cursor:pointer">1</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">2</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">3</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">›</button>
                  </div>
                </div>
              </Show>
            </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>
  );
}
