import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';

export default function ErrorReports({ authedPlayer, sessionId }) {
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({ title: '', description: '', category: 'bug', pageUrl: '' });

  const isGM = authedPlayer && authedPlayer.toLowerCase() === 'gm';

  const headers = { 'x-session-id': sessionId };

  const fetchReports = useCallback(async () => {
    try {
      const res = await axios.get('/api/errors', { headers });
      setReports(res.data || []);
    } catch (e) {
      console.error('Failed to fetch error reports', e);
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionId]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await axios.post('/api/errors', { ...form, pageUrl: form.pageUrl || window.location.pathname }, { headers });
      setForm({ title: '', description: '', category: 'bug', pageUrl: '' });
      setShowForm(false);
      fetchReports();
    } catch (err) {
      console.error('Submit failed', err);
    } finally {
      setSubmitting(false);
    }
  };

  const handleResolve = async (id, note) => {
    try {
      await axios.put(`/api/errors/${id}/resolve`, { note }, { headers });
      fetchReports();
    } catch (err) { console.error('Resolve failed', err); }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this error report?')) return;
    try {
      await axios.delete(`/api/errors/${id}`, { headers });
      fetchReports();
    } catch (err) { console.error('Delete failed', err); }
  };

  if (!authedPlayer) {
    return (
      <div className="p-6 rounded-lg bg-yellow-900/20 border border-yellow-500/30">
        <h2 className="text-xl font-bold text-yellow-300 mb-2">Login Required</h2>
        <p className="text-yellow-200">You need to be logged in to submit or view error reports.</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-white">Error Reports</h2>
        <button
          onClick={() => setShowForm(!showForm)}
          className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white font-medium transition-colors"
        >
          {showForm ? 'Cancel' : '+ New Report'}
        </button>
      </div>

      {/* Submit Form */}
      {showForm && (
        <form onSubmit={handleSubmit} className="p-4 rounded-lg bg-slate-800/80 border border-slate-600 space-y-3">
          <div>
            <label className="block text-sm text-slate-300 mb-1">Category</label>
            <select
              value={form.category}
              onChange={e => setForm({ ...form, category: e.target.value })}
              className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-white"
            >
              <option value="bug">Bug</option>
              <option value="feature">Feature Request</option>
              <option value="ui">UI / Display</option>
              <option value="data">Data / Content</option>
              <option value="other">Other</option>
            </select>
          </div>
          <div>
            <label className="block text-sm text-slate-300 mb-1">Title</label>
            <input
              type="text"
              required
              value={form.title}
              onChange={e => setForm({ ...form, title: e.target.value })}
              placeholder="Short description of the issue"
              className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-white placeholder-slate-400"
            />
          </div>
          <div>
            <label className="block text-sm text-slate-300 mb-1">Description</label>
            <textarea
              required
              value={form.description}
              onChange={e => setForm({ ...form, description: e.target.value })}
              placeholder="What happened? What did you expect? Steps to reproduce?"
              rows={4}
              className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-white placeholder-slate-400 resize-vertical"
            />
          </div>
          <button
            type="submit"
            disabled={submitting}
            className="px-6 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white font-medium transition-colors"
          >
            {submitting ? 'Submitting...' : 'Submit Report'}
          </button>
        </form>
      )}

      {/* Reports List */}
      {loading ? (
        <div className="text-center text-slate-400 py-8">Loading...</div>
      ) : reports.length === 0 ? (
        <div className="text-center text-slate-400 py-8">No error reports yet. Be the first to report one!</div>
      ) : (
        <div className="space-y-3">
          {reports.map(r => (
            <div key={r.id} className={`p-4 rounded-lg border ${r.status === 'resolved' ? 'bg-green-900/10 border-green-700/30' : 'bg-slate-800/60 border-slate-600'}`}>
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1">
                  <div className="flex flex-wrap items-center gap-2 mb-1">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${r.status === 'resolved' ? 'bg-green-800/50 text-green-300' : 'bg-yellow-800/50 text-yellow-300'}`}>
                      {r.status}
                    </span>
                    <span className="px-2 py-0.5 rounded text-xs bg-slate-700 text-slate-300">
                      {r.category}
                    </span>
                    <span className="text-xs text-slate-400">by <strong>{r.player_name}</strong></span>
                    <span className="text-xs text-slate-500">{new Date(r.created_at).toLocaleString()}</span>
                  </div>
                  <h4 className="text-white font-medium">{r.title}</h4>
                  <p className="text-slate-300 text-sm mt-1 whitespace-pre-wrap">{r.description}</p>
                  {r.page_url && <p className="text-xs text-slate-500 mt-1">Page: {r.page_url}</p>}
                  {r.resolved_by && <p className="text-xs text-green-400 mt-1">Resolved by {r.resolved_by}{r.resolved_note ? `: ${r.resolved_note}` : ''}</p>}
                </div>
                <div className="flex flex-col gap-1">
                  {isGM && r.status !== 'resolved' && (
                    <button
                      onClick={() => {
                        const note = prompt('Resolution note (optional):');
                        if (note !== null) handleResolve(r.id, note);
                      }}
                      className="px-3 py-1 rounded text-xs bg-green-700 hover:bg-green-600 text-white"
                    >
                      Resolve
                    </button>
                  )}
                  {isGM && (
                    <button
                      onClick={() => handleDelete(r.id)}
                      className="px-3 py-1 rounded text-xs bg-red-700 hover:bg-red-600 text-white"
                    >
                      Delete
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}