'use client';

import { Textarea } from '@/components/input';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api';
import { Loader2 } from 'lucide-react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';

interface Ticket {
  id: string;
  subject: string;
  status: 'awaiting_admin' | 'awaiting_user' | 'closed';
  createdAt: string;
  lastMessageAt: string;
}

interface Message {
  id: string;
  authorIsAdmin: boolean;
  body: string;
  createdAt: string;
}

export default function TicketDetail() {
  const params = useParams<{ id: string }>();
  const [data, setData] = useState<{ ticket: Ticket; messages: Message[] } | null>(null);
  const [reply, setReply] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function load() {
    if (!params?.id) return;
    apiFetch<{ ticket: Ticket; messages: Message[] }>(`/v1/support/tickets/${params.id}`)
      .then(setData)
      .catch((e) => setError((e as Error).message));
  }

  useEffect(load, [params?.id]);

  async function sendReply(e: React.FormEvent) {
    e.preventDefault();
    if (!params?.id || reply.trim().length === 0) return;
    setBusy(true);
    setError(null);
    try {
      await apiFetch(`/v1/support/tickets/${params.id}/messages`, {
        method: 'POST',
        body: JSON.stringify({ body: reply }),
      });
      setReply('');
      load();
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setBusy(false);
    }
  }

  if (!data && !error) {
    return (
      <div className="mx-auto max-w-3xl px-6 py-12 text-center">
        <Loader2 className="mx-auto animate-spin text-[--color-fg-muted]" size={20} />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="mx-auto max-w-3xl px-6 py-12">
        <p className="text-[13px] text-[--color-danger]">{error ?? 'Ticket not found.'}</p>
        <Link href="/settings/support" className="mt-3 inline-block text-[12px] text-[--color-fg-muted] hover:text-[--color-fg]">
          ← Back to support
        </Link>
      </div>
    );
  }

  const { ticket, messages } = data;
  const isClosed = ticket.status === 'closed';

  return (
    <div className="mx-auto max-w-3xl px-6 py-10">
      <Link
        href="/settings/support"
        className="text-[12px] text-[--color-fg-muted] hover:text-[--color-fg]"
      >
        ← All tickets
      </Link>
      <div className="mt-3 flex items-baseline justify-between gap-3">
        <h1 className="text-[22px] font-semibold tracking-tight">{ticket.subject}</h1>
        <span className="mono text-[10.5px] uppercase tracking-wider text-[--color-fg-subtle]">
          {ticket.status.replace('_', ' ')}
        </span>
      </div>

      <div className="mt-6 space-y-3">
        {messages.map((m) => (
          <div
            key={m.id}
            className={`panel p-4 ${m.authorIsAdmin ? 'border-[--color-accent]/40' : ''}`}
          >
            <div className="flex items-baseline justify-between">
              <span
                className={`text-[11.5px] font-medium ${m.authorIsAdmin ? 'text-[--color-accent]' : 'text-[--color-fg]'}`}
              >
                {m.authorIsAdmin ? 'Support' : 'You'}
              </span>
              <span className="text-[10.5px] text-[--color-fg-subtle]">
                {new Date(m.createdAt).toLocaleString()}
              </span>
            </div>
            <p className="mt-2 whitespace-pre-wrap text-[13px] leading-relaxed text-[--color-fg-muted]">
              {m.body}
            </p>
          </div>
        ))}
      </div>

      {!isClosed && (
        <form onSubmit={sendReply} className="panel mt-6 space-y-3 p-4">
          <Textarea
            value={reply}
            onChange={(e) => setReply(e.target.value)}
            rows={4}
            maxLength={10_000}
            placeholder="Your reply…"
          />
          {error && <p className="text-[12.5px] text-[--color-danger]">{error}</p>}
          <div className="flex justify-end">
            <Button
              variant="primary"
              size="md"
              type="submit"
              disabled={busy || reply.trim().length === 0}
            >
              {busy ? 'Sending…' : 'Send reply'}
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}
