import { useEffect, useState } from 'react';
import { useOutletContext } from 'react-router-dom';
import { api } from '../api/client';
import Header from '../components/Layout/Header';
import { formatDateTime } from '../utils/date';

export default function SupportPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [tickets, setTickets] = useState([]);
  const [subject, setSubject] = useState('');
  const [message, setMessage] = useState('');
  const [sent, setSent] = useState(false);

  const load = () => api.get('/support').then(({ data }) => setTickets(data.tickets));

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    await api.post('/support', { subject, message });
    setSubject('');
    setMessage('');
    setSent(true);
    load();
    setTimeout(() => setSent(false), 3000);
  };

  return (
    <div>
      <Header title="پشتیبانی" user={user} onMenuClick={() => setMobileOpen?.(true)} />

      <form onSubmit={handleSubmit} className="card mb-6 max-w-lg space-y-4">
        <h3 className="font-bold">ارسال تیکت جدید</h3>
        {sent && <p className="text-emerald-400 text-sm">تیکت با موفقیت ثبت شد</p>}
        <input className="input-field" placeholder="موضوع" value={subject} onChange={(e) => setSubject(e.target.value)} required />
        <textarea className="input-field min-h-[100px]" placeholder="پیام" value={message} onChange={(e) => setMessage(e.target.value)} required />
        <button type="submit" className="btn-primary">
          ارسال
        </button>
      </form>

      <div className="space-y-3">
        {tickets.map((t) => (
          <div key={t.id} className="card">
            <div className="flex justify-between mb-2">
              <p className="font-medium">{t.subject}</p>
              <span className="text-xs text-gray-500">{formatDateTime(t.createdAt)}</span>
            </div>
            <p className="text-sm text-gray-400">{t.message}</p>
            <span className="inline-block mt-2 text-xs px-2 py-1 rounded bg-navy-700">{t.status}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
