'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { usePortalAuthStore } from '@/lib/portal-auth-store';
import portalApi from '@/lib/portal-api';
import { formatDate } from '@/lib/utils';

interface PortalTicket {
  id: string;
  subject: string;
  status: string;
  type?: string;
  createdAt: string;
}

const statusBadge: Record<string, { bg: string; text: string }> = {
  OPEN:        { bg: '#DBEAFE', text: '#1D4ED8' },
  IN_PROGRESS: { bg: '#FEF9C3', text: '#CA8A04' },
  RESOLVED:    { bg: '#DCFCE7', text: '#16A34A' },
  CLOSED:      { bg: '#F1F5F9', text: '#64748B' },
};

export default function PortalTicketsPage() {
  const router = useRouter();
  const { isAuthenticated } = usePortalAuthStore();
  const [mounted, setMounted] = useState(false);
  const [tickets, setTickets] = useState<PortalTicket[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState({ subject: '', description: '' });
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');

  useEffect(() => { setMounted(true); }, []);

  useEffect(() => {
    if (!mounted) return;
    if (!isAuthenticated) { router.replace('/portal/login'); return; }
    loadTickets();
  }, [mounted, isAuthenticated, router]);

  const loadTickets = () => {
    setLoading(true);
    portalApi.get('/api/v1/portal/tickets')
      .then((res) => {
        const data = res.data;
        setTickets(Array.isArray(data) ? data : data.data ?? []);
      })
      .catch(() => setError('Failed to load tickets.'))
      .finally(() => setLoading(false));
  };

  const handleSubmitTicket = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError('');
    setSubmitting(true);
    try {
      await portalApi.post('/api/v1/portal/tickets', form);
      setShowModal(false);
      setForm({ subject: '', description: '' });
      loadTickets();
    } catch (err: unknown) {
      setSubmitError((err as any)?.response?.data?.message ?? 'Failed to submit ticket.');
    } finally {
      setSubmitting(false);
    }
  };

  if (!mounted || !isAuthenticated) return null;

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '32px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Link href="/portal/dashboard" style={{ fontSize: 13, color: '#0891B2', textDecoration: 'none' }}>
            ← Back
          </Link>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', margin: 0 }}>Support Tickets</h1>
        </div>
        <button
          onClick={() => setShowModal(true)}
          style={{ backgroundColor: '#059669', color: '#ffffff', border: 'none', borderRadius: 8, padding: '9px 18px', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}
        >
          + New Ticket
        </button>
      </div>

      {error && (
        <div style={{ backgroundColor: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '12px 16px', color: '#DC2626', fontSize: 14, marginBottom: 20 }}>
          {error}
        </div>
      )}

      <div style={{ backgroundColor: '#ffffff', borderRadius: 12, border: '1px solid #E2E8F0', overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Loading…</div>
        ) : tickets.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>
            No tickets yet. Click &quot;New Ticket&quot; to raise a support request.
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#F8FAFC', borderBottom: '1px solid #E2E8F0' }}>
                {['Subject', 'Type', 'Status', 'Date'].map((h) => (
                  <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {tickets.map((t, i) => {
                const badge = statusBadge[t.status] ?? statusBadge.CLOSED;
                return (
                  <tr key={t.id} style={{ borderBottom: i < tickets.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
                    <td style={{ padding: '12px 16px', fontSize: 14, color: '#0F172A', fontWeight: 500 }}>{t.subject}</td>
                    <td style={{ padding: '12px 16px', fontSize: 13, color: '#64748B' }}>{t.type ?? '—'}</td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{ fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 20, backgroundColor: badge.bg, color: badge.text }}>
                        {t.status.replace('_', ' ')}
                      </span>
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 13, color: '#64748B' }}>{formatDate(t.createdAt)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* New Ticket Modal */}
      {showModal && (
        <div style={{ position: 'fixed', inset: 0, backgroundColor: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 24 }}>
          <div style={{ backgroundColor: '#ffffff', borderRadius: 12, padding: 28, width: '100%', maxWidth: 480, boxShadow: '0 20px 60px rgba(0,0,0,0.15)' }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', marginBottom: 4 }}>New Support Ticket</h2>
            <p style={{ fontSize: 13, color: '#64748B', marginBottom: 20 }}>Describe your issue and our team will get back to you.</p>

            {submitError && (
              <div style={{ backgroundColor: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '10px 14px', color: '#DC2626', fontSize: 13, marginBottom: 16 }}>
                {submitError}
              </div>
            )}

            <form onSubmit={handleSubmitTicket} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, color: '#374151', marginBottom: 6 }}>Subject</label>
                <input
                  type="text"
                  required
                  value={form.subject}
                  onChange={(e) => setForm({ ...form, subject: e.target.value })}
                  placeholder="e.g. Internet not working"
                  style={inputStyle}
                />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, color: '#374151', marginBottom: 6 }}>Description</label>
                <textarea
                  required
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  placeholder="Please describe your issue in detail…"
                  rows={4}
                  style={{ ...inputStyle, resize: 'vertical', fontFamily: 'inherit' }}
                />
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
                <button
                  type="button"
                  onClick={() => { setShowModal(false); setSubmitError(''); setForm({ subject: '', description: '' }); }}
                  style={{ fontSize: 14, color: '#64748B', background: 'none', border: '1px solid #E2E8F0', borderRadius: 8, padding: '9px 18px', cursor: 'pointer' }}
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  style={{ backgroundColor: submitting ? '#67C5DD' : '#0891B2', color: '#ffffff', border: 'none', borderRadius: 8, padding: '9px 18px', fontSize: 14, fontWeight: 600, cursor: submitting ? 'not-allowed' : 'pointer' }}
                >
                  {submitting ? 'Submitting…' : 'Submit Ticket'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

const inputStyle: React.CSSProperties = {
  width: '100%',
  padding: '9px 12px',
  border: '1px solid #D1D5DB',
  borderRadius: 8,
  fontSize: 14,
  color: '#0F172A',
  backgroundColor: '#ffffff',
  outline: 'none',
  boxSizing: 'border-box',
};
