'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';

type TicketRow = {
  id: number; ticketNo: string; category: string; source: string | null; customerPhone: string;
  status: string; assignedTo: { name: string } | null;
};
type TicketMessage = { id: number; sender: string; body: string; isInternalNote: boolean; createdAt: string; createdBy: { name: string } | null };
type TicketDetail = TicketRow & { messages: TicketMessage[] };

const CATEGORIES = ['All', 'Buying', 'Sending Quote', 'Technical Support', 'Maintenance', 'Complaint', 'General'];
const NEW_TICKET_CATEGORIES = CATEGORIES.filter((c) => c !== 'All');
const emptyNewTicket = { category: 'General', customerPhone: '', message: '' };

export default function TicketsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [tickets, setTickets] = useState<TicketRow[]>([]);
  const [counts, setCounts] = useState<Record<string, number>>({});
  const [category, setCategory] = useState('All');
  const [selected, setSelected] = useState<TicketDetail | null>(null);
  const [reply, setReply] = useState('');
  const [isNote, setIsNote] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [showNewTicket, setShowNewTicket] = useState(false);
  const [newTicket, setNewTicket] = useState(emptyNewTicket);
  const [creating, setCreating] = useState(false);

  async function loadList() {
    if (!accessToken || !appSecretProof) return;
    try {
      const d = await adminApiFetch(`/admin/tickets?category=${encodeURIComponent(category)}`, accessToken, appSecretProof);
      setTickets(d.tickets || []);
      setCounts(d.counts || {});
    } catch { setError('You do not have permission to view this page.'); }
  }
  useEffect(() => { loadList(); }, [accessToken, appSecretProof, category]); // eslint-disable-line react-hooks/exhaustive-deps

  async function openTicket(id: number) {
    if (!accessToken || !appSecretProof) return;
    const d = await adminApiFetch(`/admin/tickets/${id}`, accessToken, appSecretProof);
    setSelected(d.ticket);
  }

  async function submitNewTicket(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !newTicket.customerPhone.trim() || !newTicket.message.trim()) return;
    setCreating(true);
    try {
      const d = await adminApiFetch('/admin/tickets', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(newTicket) });
      show('success', `${d.ticket.ticketNo} created.`);
      setNewTicket(emptyNewTicket);
      setShowNewTicket(false);
      loadList();
      openTicket(d.ticket.id);
    } catch { show('error', 'Could not create that ticket.'); }
    finally { setCreating(false); }
  }

  async function sendReply(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !selected || !reply.trim()) return;
    try {
      await adminApiFetch(`/admin/tickets/${selected.id}/messages`, accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ body: reply, isInternalNote: isNote }),
      });
      show('success', isNote ? 'Internal note added.' : 'Reply sent.');
      setReply('');
      openTicket(selected.id);
    } catch { show('error', 'Could not send that message.'); }
  }

  async function updateStatus(status: string) {
    if (!accessToken || !appSecretProof || !selected) return;
    try {
      await adminApiFetch(`/admin/tickets/${selected.id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      setSelected({ ...selected, status });
      show('success', `Ticket marked ${status.replace('_', ' ')}.`);
      loadList();
    } catch { show('error', 'Could not update that ticket.'); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="flex h-[calc(100vh-64px-48px)] -m-6">
      <div className="w-[380px] border-r border-brand-border bg-white overflow-y-auto">
        <div className="p-4 border-b border-brand-border">
          <div className="flex justify-between items-center">
            <p className="font-bold text-sm">Communication Hub</p>
            <button onClick={() => setShowNewTicket(true)} className="text-[10px] bg-brand-red text-white px-2.5 py-1 rounded-full transition-transform hover:scale-105">+ New</button>
          </div>
          <div className="flex gap-1 mt-2 flex-wrap">
            {CATEGORIES.map((c) => (
              <button key={c} onClick={() => setCategory(c)} className={`text-[10px] px-2 py-1 border rounded-full transition-colors ${category === c ? 'bg-brand-red text-white border-brand-red' : 'bg-brand-bg border-brand-border'}`}>
                {c} {counts[c] !== undefined ? counts[c] : ''}
              </button>
            ))}
          </div>
        </div>
        {tickets.map((t) => (
          <div key={t.id} onClick={() => openTicket(t.id)} className={`p-3 border-b border-brand-border cursor-pointer transition-colors hover:bg-brand-bg ${selected?.id === t.id ? 'bg-brand-bg border-l-2 border-l-brand-red' : ''}`}>
            <div className="flex justify-between"><p className="font-mono text-xs font-bold">{t.ticketNo}</p><span className="text-[10px] px-1.5 py-0.5 rounded-full bg-brand-border">{t.category}</span></div>
            <p className="text-[10px] text-gray-500 mt-1">{t.customerPhone} &bull; {t.source || '—'} &bull; {t.assignedTo?.name || 'Unassigned'} &bull; {t.status}</p>
          </div>
        ))}
        {tickets.length === 0 && <p className="p-4 text-xs text-gray-400">No tickets in this category.</p>}
      </div>

      <div className="flex-1 bg-brand-bg p-4 overflow-y-auto">
        {selected ? (
          <div className="space-y-4">
            <div className="bg-white p-4 rounded-xl border border-brand-border">
              <div className="flex justify-between items-start">
                <p className="font-bold text-sm">{selected.ticketNo} &bull; {selected.category}</p>
                <select value={selected.status} onChange={(e) => updateStatus(e.target.value)} className="text-[10px] rounded-full px-2 py-1 bg-brand-bg border border-brand-border">
                  {['OPEN', 'UNDER_REVIEW', 'ESCALATED', 'RESOLVED'].map((s) => <option key={s} value={s}>{s.replace('_', ' ')}</option>)}
                </select>
              </div>
              <p className="text-[11px] text-gray-500 mt-2">Customer {selected.customerPhone} &bull; Source {selected.source || '—'}</p>
              <div className="flex gap-2 mt-3">
                <a href={`https://wa.me/${selected.customerPhone.replace(/[^0-9]/g, '')}`} target="_blank" rel="noopener noreferrer"
                  className="bg-green-600 text-white text-xs px-3 py-1.5 rounded-lg transition-transform hover:scale-105">
                  WhatsApp {selected.customerPhone}
                </a>
                <a href="mailto:info@lussavara.co.tz" className="border border-brand-border text-xs px-3 py-1.5 rounded-lg transition-colors hover:bg-brand-bg">
                  Email
                </a>
              </div>
            </div>

            {selected.category === 'Sending Quote' && <QuoteCalculator />}

            <div className="bg-white p-4 rounded-xl border border-brand-border">
              <p className="font-semibold text-xs mb-2">Chat Thread</p>
              <div className="space-y-2 text-xs">
                {selected.messages.map((m) => (
                  m.isInternalNote ? (
                    <div key={m.id} className="bg-yellow-50 border border-yellow-200 p-2 rounded-lg text-[10px] animate-fadeInUp">Internal Note ({m.createdBy?.name || 'Admin'}): {m.body}</div>
                  ) : (
                    <div key={m.id} className={`p-2 rounded-lg max-w-[80%] animate-fadeInUp ${m.sender === 'ADMIN' ? 'bg-brand-red text-white ml-auto' : 'bg-gray-100'}`}>{m.body}</div>
                  )
                ))}
                {selected.messages.length === 0 && <p className="text-gray-400">No messages yet.</p>}
              </div>
              <form onSubmit={sendReply} className="flex gap-2 mt-3">
                <input value={reply} onChange={(e) => setReply(e.target.value)} placeholder="Type reply…" className="flex-1 border border-brand-border rounded-full px-3 py-2 text-xs" />
                <label className="text-[10px] flex items-center gap-1"><input type="checkbox" checked={isNote} onChange={(e) => setIsNote(e.target.checked)} /> Internal note</label>
                <button className={`px-4 py-2 rounded-full text-xs text-white transition-transform hover:scale-105 ${isNote ? 'bg-yellow-600' : 'bg-brand-red'}`}>Send</button>
              </form>
            </div>
          </div>
        ) : <p className="text-sm text-gray-500 p-4">Select a ticket to view the thread, or create a new one for a phoned-in or walk-in customer.</p>}
      </div>

      {showNewTicket && (
        <Modal title="New Ticket" onClose={() => setShowNewTicket(false)}>
          <form onSubmit={submitNewTicket} className="space-y-3">
            <p className="text-xs text-gray-500">For a customer issue that came in by phone or in person — not through the website.</p>
            <select required value={newTicket.category} onChange={(e) => setNewTicket({ ...newTicket, category: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              {NEW_TICKET_CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
            <input required placeholder="Customer phone +255…" value={newTicket.customerPhone} onChange={(e) => setNewTicket({ ...newTicket, customerPhone: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <textarea required placeholder="What did the customer say?" value={newTicket.message} onChange={(e) => setNewTicket({ ...newTicket, message: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" rows={3} />
            <button disabled={creating} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {creating ? 'Creating…' : 'Create Ticket'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}

/**
 * Quick-reference calculator for a "Sending Quote" ticket — subtotal in,
 * VAT/delivery/total computed live. Deliberately not tied to creating a
 * real Quote record: tickets only have a customerPhone, not a linked
 * Client, so there's no clean client to attach a Quote to from here yet.
 * This is for the back-and-forth of agreeing a number over WhatsApp before
 * a real quote gets raised properly from Quotes → New Quote.
 */
function QuoteCalculator() {
  const [subtotal, setSubtotal] = useState('');
  const [freeDelivery, setFreeDelivery] = useState(true);
  const [deliveryFee, setDeliveryFee] = useState('');

  const sub = Number(subtotal) || 0;
  const vat = sub * 0.18;
  const delivery = freeDelivery ? 0 : Number(deliveryFee) || 0;
  const total = sub + vat + delivery;

  return (
    <div className="bg-white p-4 rounded-xl border border-brand-border">
      <p className="font-semibold text-xs mb-2">Quick Quote Calculator</p>
      <div className="grid grid-cols-2 gap-2 mb-2">
        <input type="number" placeholder="Subtotal TZS" value={subtotal} onChange={(e) => setSubtotal(e.target.value)}
          className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
        <label className="flex items-center gap-1.5 text-xs text-gray-500">
          <input type="checkbox" checked={freeDelivery} onChange={(e) => setFreeDelivery(e.target.checked)} /> Free delivery
        </label>
        {!freeDelivery && (
          <input type="number" placeholder="Delivery fee TZS" value={deliveryFee} onChange={(e) => setDeliveryFee(e.target.value)}
            className="border border-brand-border rounded-lg px-2 py-1.5 text-xs col-span-2 animate-fadeIn" />
        )}
      </div>
      <div className="grid grid-cols-4 gap-2 bg-brand-bg rounded-lg p-2.5 text-xs">
        <div><p className="text-gray-400">Subtotal</p><p className="font-semibold">{sub.toLocaleString()}</p></div>
        <div><p className="text-gray-400">VAT 18%</p><p className="font-semibold">{vat.toLocaleString()}</p></div>
        <div><p className="text-gray-400">Delivery</p><p className="font-semibold">{freeDelivery ? 'Free' : delivery.toLocaleString()}</p></div>
        <div><p className="text-gray-400">Total</p><p className="font-bold">{total.toLocaleString()}</p></div>
      </div>
      <p className="text-[10px] text-gray-400 mt-2">Once agreed, raise the official quote from Quotes → New Quote for a proper PDF.</p>
    </div>
  );
}
