'use client';

import { useState } from 'react';
import { MessageSquare } from 'lucide-react';
import { timeAgo } from '@/utils';

const API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4100/api';

interface CommentUser { id: number; name: string; avatar?: string | null }
interface CommentNode {
  id: number;
  content: string;
  createdAt: string;
  guestName?: string | null;
  user?: CommentUser | null;
  replies?: CommentNode[];
}

const inputClass =
  'w-full rounded-md border border-surface bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand-500 disabled:opacity-60';

function Avatar({ name }: { name: string }) {
  return (
    <span className="grid h-9 w-9 flex-shrink-0 place-items-center rounded-full bg-brand-900 text-xs font-bold text-white">
      {name?.[0]?.toUpperCase() || '?'}
    </span>
  );
}

function CommentItem({ node }: { node: CommentNode }) {
  const name = node.user?.name || node.guestName || 'Anonymous';
  return (
    <div className="flex gap-3">
      <Avatar name={name} />
      <div className="min-w-0 flex-1">
        <div className="flex flex-wrap items-baseline gap-x-2">
          <span className="text-sm font-semibold text-body">{name}</span>
          <span className="text-xs text-muted">{timeAgo(node.createdAt)}</span>
        </div>
        <p className="mt-1 whitespace-pre-line text-sm leading-relaxed text-body">{node.content}</p>
        {node.replies && node.replies.length > 0 && (
          <div className="mt-4 space-y-4 border-l-2 border-surface pl-4">
            {node.replies.map((r) => (
              <CommentItem key={r.id} node={r} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default function Comments({ articleId, initial = [] }: { articleId: number; initial?: CommentNode[] }) {
  const [comments] = useState<CommentNode[]>(initial);
  const [form, setForm] = useState({ guestName: '', guestEmail: '', content: '' });
  const [status, setStatus] = useState<'idle' | 'sending' | 'sent' | 'error'>('idle');
  const [error, setError] = useState('');

  const sending = status === 'sending';

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.content.trim() || !form.guestName.trim()) {
      setStatus('error');
      setError('Please add your name and a comment.');
      return;
    }
    setStatus('sending');
    setError('');
    try {
      const res = await fetch(`${API}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          articleId,
          content: form.content,
          guestName: form.guestName,
          guestEmail: form.guestEmail || undefined,
        }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.success) throw new Error(json.message || 'Could not submit your comment.');
      setStatus('sent');
      setForm({ guestName: '', guestEmail: '', content: '' });
    } catch (err: any) {
      setStatus('error');
      setError(err.message || 'Could not submit your comment.');
    }
  }

  return (
    <section className="mt-12 border-t border-surface pt-8">
      <h2 className="flex items-center gap-2 font-serif text-xl font-bold text-body">
        <MessageSquare size={20} className="text-brand-700 dark:text-brand-300" />
        Comments {comments.length > 0 && <span className="text-muted">({comments.length})</span>}
      </h2>

      {/* Form */}
      <form onSubmit={submit} className="mt-6 rounded-card border border-surface bg-surface p-5">
        {status === 'sent' && (
          <div className="mb-4 rounded-md border border-emerald-500/40 bg-emerald-50 px-4 py-3 text-sm font-medium text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300">
            Thanks — your comment was submitted and will appear once approved by a moderator.
          </div>
        )}
        {status === 'error' && (
          <div className="mb-4 rounded-md border border-red-500/40 bg-red-50 px-4 py-3 text-sm font-medium text-red-700 dark:bg-red-500/10 dark:text-red-300">
            {error}
          </div>
        )}
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <input
            className={inputClass}
            placeholder="Your name *"
            value={form.guestName}
            onChange={(e) => setForm((f) => ({ ...f, guestName: e.target.value }))}
            disabled={sending}
          />
          <input
            className={inputClass}
            type="email"
            placeholder="Email (optional, not published)"
            value={form.guestEmail}
            onChange={(e) => setForm((f) => ({ ...f, guestEmail: e.target.value }))}
            disabled={sending}
          />
        </div>
        <textarea
          className={`${inputClass} mt-3 resize-none`}
          rows={4}
          placeholder="Join the discussion…"
          value={form.content}
          onChange={(e) => setForm((f) => ({ ...f, content: e.target.value }))}
          disabled={sending}
        />
        <div className="mt-3 flex items-center justify-between">
          <p className="text-xs text-muted">Comments are moderated before publishing.</p>
          <button
            type="submit"
            disabled={sending}
            className="rounded-md bg-brand-900 px-5 py-2 text-sm font-semibold text-white transition hover:bg-brand-800 disabled:opacity-60"
          >
            {sending ? 'Posting…' : 'Post Comment'}
          </button>
        </div>
      </form>

      {/* List */}
      <div className="mt-8 space-y-6">
        {comments.length === 0 ? (
          <p className="text-sm text-muted">No comments yet. Be the first to share your thoughts.</p>
        ) : (
          comments.map((c) => <CommentItem key={c.id} node={c} />)
        )}
      </div>
    </section>
  );
}
