import { useCallback, useEffect, useState } from 'react';
import DiscussionSettingsSection from './DiscussionSettingsSection.js';
import { ScreenHeader } from './ScreenHeader.js';
import type { Comment, CommentStatus } from '@platform-modules/comments';
import {
  Badge,
  Button,
  ErrorState,
  Table,
  Tabs,
  TabsContent,
  TabsList,
  Skeleton,
  TabsTrigger,
  useToast,
  type BadgeProps,
} from '@platform-modules/ui-primitives';

type QueueResponse = {
  items: Comment[];
  nextCursor: string | null;
};

const TABS: { id: CommentStatus; label: string }[] = [
  { id: 'pending', label: 'Pending' },
  { id: 'spam', label: 'Spam' },
  { id: 'published', label: 'Published' },
];

function statusTone(status: CommentStatus): NonNullable<BadgeProps['tone']> {
  if (status === 'published') return 'success';
  if (status === 'spam') return 'danger';
  return 'warning';
}

function authorLabel(comment: Comment): string {
  if (comment.author.kind === 'user') return `Member ${comment.author.userId.slice(0, 8)}`;
  const guest = comment.author;
  return guest.email ? `${guest.name} (${guest.email})` : guest.name;
}

export default function CommentsScreen() {
  const { toast } = useToast();
  const [status, setStatus] = useState<CommentStatus>('pending');
  const [items, setItems] = useState<Comment[]>([]);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [busyId, setBusyId] = useState<string | null>(null);

  const load = useCallback(async (tab: CommentStatus, cursor?: string, append = false) => {
    setLoading(!append);
    setError('');
    try {
      const params = new URLSearchParams({ status: tab });
      if (cursor) params.set('cursor', cursor);
      const res = await fetch(`/api/admin/comments?${params}`, { credentials: 'same-origin' });
      const body: unknown = await res.json().catch(() => null);
      if (!res.ok) {
        const message =
          (body as { error?: { message?: string } } | null)?.error?.message ?? res.statusText;
        throw new Error(message);
      }
      const data = body as QueueResponse;
      setItems((prev) => (append ? [...prev, ...data.items] : data.items));
      setNextCursor(data.nextCursor);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Comments could not load.');
      if (!append) setItems([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function moderate(action: 'approve' | 'spam' | 'trash' | 'delete', id: string) {
    setBusyId(id);
    try {
      const res = await fetch('/api/admin/comments', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'content-type': 'application/json', origin: window.location.origin },
        body: JSON.stringify({ action, id }),
      });
      const body: unknown = await res.json().catch(() => null);
      if (!res.ok) {
        const message =
          (body as { error?: { message?: string } } | null)?.error?.message ?? res.statusText;
        throw new Error(message);
      }
      toast({ title: 'Comment updated', tone: 'success' });
      await load(status);
    } catch (e) {
      toast({
        title: e instanceof Error ? e.message : 'That action could not complete.',
        tone: 'danger',
      });
    } finally {
      setBusyId(null);
    }
  }

  return (
    <>
      <DiscussionSettingsSection />
      <hr className="admin-divider" aria-hidden="true" />
    <section aria-labelledby="comments-heading">
      {loading && items.length === 0 ? (
        <div className="flex flex-col gap-4" aria-hidden="true">
          <Skeleton variant="heading" />
          <Skeleton variant="block" />
        </div>
      ) : null}
      <ScreenHeader
        headingId="comments-heading"
        title="Comments"
        description="Moderate guest and member comments across all posts."
      />

      <Tabs value={status} onValueChange={(v) => setStatus(v as typeof status)}>
        <TabsList aria-label="Comment status">
          {TABS.map((tab) => (
            <TabsTrigger key={tab.id} value={tab.id}>
              {tab.label}
            </TabsTrigger>
          ))}
        </TabsList>

        {TABS.map((tab) => (
          <TabsContent key={tab.id} value={tab.id}>
            {error ? (
              <ErrorState
                variant="inline"
                title="Comments couldn't load"
                message={error}
                action={
                  <Button tone="accent" radius="sm" size="sm" type="button" onClick={() => void load(status)}>
                    Try again
                  </Button>
                }
              />
            ) : null}

            {!error && !loading && items.length === 0 ? (
              <div className="admin-empty">
                <p>No comments in this queue.</p>
              </div>
            ) : null}

            {!error && items.length > 0 ? (
              <>
                <Table caption="Comment moderation queue">
                  <Table.Head>
                    <Table.Row>
                      <Table.Th scope="col">Author</Table.Th>
                      <Table.Th scope="col">Target</Table.Th>
                      <Table.Th scope="col">Comment</Table.Th>
                      <Table.Th scope="col">Status</Table.Th>
                      <Table.Th scope="col">Actions</Table.Th>
                    </Table.Row>
                  </Table.Head>
                  <Table.Body>
                    {items.map((comment) => (
                      <Table.Row key={comment.id}>
                        <Table.Td>{authorLabel(comment)}</Table.Td>
                        <Table.Td>
                          <span className="font-mono text-xs">
                            {comment.target.type}:{comment.target.id.slice(0, 8)}…
                          </span>
                        </Table.Td>
                        <Table.Td>{comment.body}</Table.Td>
                        <Table.Td>
                          <Badge tone={statusTone(comment.status)}>{comment.status}</Badge>
                        </Table.Td>
                        <Table.Td>
                          <div className="flex flex-wrap gap-2">
                            {comment.status !== 'published' ? (
                              <Button
                                tone="accent"
                                radius="sm"
                                size="sm"
                                type="button"
                                disabled={busyId === comment.id}
                                onClick={() => void moderate('approve', comment.id)}
                              >
                                Approve
                              </Button>
                            ) : null}
                            {comment.status !== 'spam' ? (
                              <Button
                                tone="surface"
                                radius="sm"
                                size="sm"
                                type="button"
                                disabled={busyId === comment.id}
                                onClick={() => void moderate('spam', comment.id)}
                              >
                                Spam
                              </Button>
                            ) : null}
                            {comment.status !== 'trashed' ? (
                              <Button
                                tone="surface"
                                radius="sm"
                                size="sm"
                                type="button"
                                disabled={busyId === comment.id}
                                onClick={() => void moderate('trash', comment.id)}
                              >
                                Trash
                              </Button>
                            ) : null}
                            <Button
                              tone="danger"
                              radius="sm"
                              size="sm"
                              type="button"
                              disabled={busyId === comment.id}
                              onClick={() => void moderate('delete', comment.id)}
                            >
                              Delete
                            </Button>
                          </div>
                        </Table.Td>
                      </Table.Row>
                    ))}
                  </Table.Body>
                </Table>
                {nextCursor ? (
                  <div className="mt-6">
                    <Button
                      tone="surface"
                      radius="sm"
                      size="sm"
                      type="button"
                      disabled={loading}
                      onClick={() => void load(status, nextCursor, true)}
                    >
                      Load more
                    </Button>
                  </div>
                ) : null}
              </>
            ) : null}
          </TabsContent>
        ))}
      </Tabs>
    </section>
    </>
  );
}
