import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Textarea } from '@/components/ui/textarea';
import { useApiSWR } from '@/hooks/useSWR';
import { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import { TMarketComment } from '@/types/market.types';
import { router, usePage } from '@inertiajs/react';
import {
  ArrowBendDownRightIcon,
  HeartIcon,
  TrashIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

dayjs.extend(relativeTime);

type TPageProps = {
  auth: { user: { id: number; name: string } };
};

type TPaginated = {
  data: TMarketComment[];
  current_page: number;
  last_page: number;
};

function CommentAvatar({ name }: { name: string }) {
  return (
    <Avatar className="size-8 shrink-0">
      <AvatarFallback className="text-xs font-semibold uppercase">
        {name.slice(0, 2)}
      </AvatarFallback>
    </Avatar>
  );
}

interface CommentItemProps {
  comment: TMarketComment;
  currentUserId: number | null;
  onLike: (id: number) => void;
  onDelete: (id: number) => void;
  onReplySubmit: (parentId: number, content: string) => Promise<void>;
  depth?: number;
}

function CommentItem({
  comment,
  currentUserId,
  onLike,
  onDelete,
  onReplySubmit,
  depth = 0,
}: CommentItemProps) {
  const { t } = useTranslation();
  const [showReplyBox, setShowReplyBox] = useState(false);
  const [replyContent, setReplyContent] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleReply = async () => {
    if (!replyContent.trim()) return;
    setSubmitting(true);
    await onReplySubmit(comment.id, replyContent.trim());
    setReplyContent('');
    setShowReplyBox(false);
    setSubmitting(false);
  };

  return (
    <div className={depth > 0 ? 'mt-3 ml-10' : ''}>
      <div className="flex gap-3">
        <CommentAvatar name={comment.user.name} />
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <button
              className="text-sm font-semibold hover:underline"
              onClick={() => router.visit(`/users/${comment.user.id}`)}
            >
              {comment.user.name}
            </button>
            <span className="text-xs text-black/40 dark:text-white/40">
              {dayjs(comment.created_at).fromNow()}
            </span>
          </div>
          <p className="mt-1 text-sm leading-relaxed text-black/80 dark:text-white/80">
            {comment.content}
          </p>
          <div className="mt-2 flex items-center gap-3">
            <button
              onClick={() => onLike(comment.id)}
              className={`flex items-center gap-1 text-xs transition-colors ${
                comment.is_liked
                  ? 'text-red-500'
                  : 'text-black/40 hover:text-red-400 dark:text-white/40'
              }`}
            >
              <HeartIcon
                weight={comment.is_liked ? 'fill' : 'regular'}
                className="size-3.5"
              />
              {comment.likes_count > 0 && <span>{comment.likes_count}</span>}
            </button>
            {depth === 0 && currentUserId !== null && (
              <button
                onClick={() => setShowReplyBox((v) => !v)}
                className="flex items-center gap-1 text-xs text-black/40 transition-colors hover:text-black/70 dark:text-white/40 dark:hover:text-white/70"
              >
                <ArrowBendDownRightIcon className="size-3.5" />
                {t('Reply')}
              </button>
            )}
            {currentUserId === comment.user_id && (
              <button
                onClick={() => onDelete(comment.id)}
                className="flex items-center gap-1 text-xs text-black/30 transition-colors hover:text-destructive dark:text-white/30"
              >
                <TrashIcon className="size-3.5" />
              </button>
            )}
          </div>

          {showReplyBox && (
            <div className="mt-3 flex gap-2">
              <Textarea
                placeholder={t('Write a reply…')}
                value={replyContent}
                onChange={(e) => setReplyContent(e.target.value)}
                className="min-h-10 text-sm"
                rows={2}
              />
              <div className="flex flex-col gap-1.5">
                <Button
                  size="sm"
                  onClick={handleReply}
                  disabled={submitting || !replyContent.trim()}
                >
                  {t('Send')}
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => {
                    setShowReplyBox(false);
                    setReplyContent('');
                  }}
                >
                  {t('Cancel')}
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>

      {comment.replies && comment.replies.length > 0 && (
        <div className="mt-1 space-y-3 border-l border-black/5 pl-3 dark:border-white/5">
          {comment.replies.map((reply) => (
            <CommentItem
              key={reply.id}
              comment={reply}
              currentUserId={currentUserId}
              onLike={onLike}
              onDelete={onDelete}
              onReplySubmit={onReplySubmit}
              depth={1}
            />
          ))}
        </div>
      )}
    </div>
  );
}

interface MarketCommentsProps {
  slug: string;
}

export default function MarketComments({ slug }: MarketCommentsProps) {
  const { t } = useTranslation();
  const { auth } = usePage<TPageProps>().props;
  const currentUserId = auth?.user?.id ?? null;

  const [newComment, setNewComment] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const { data, isLoading, mutate } = useApiSWR<TPaginated>(
    slug ? `/markets/${slug}/comments` : null,
  );

  const comments = data?.data ?? [];

  const handlePost = async () => {
    if (!newComment.trim()) return;
    setSubmitting(true);
    try {
      await request.post(`/api/user/markets/${slug}/comments`, {
        content: newComment.trim(),
      });
      setNewComment('');
      toast.success(t('Comment posted.'));
      mutate();
    } catch (err) {
      handleApiError(err);
    } finally {
      setSubmitting(false);
    }
  };

  const handleReplySubmit = async (parentId: number, content: string) => {
    try {
      await request.post(`/api/user/comments/${parentId}/replies`, { content });
      toast.success(t('Reply posted.'));
      mutate();
    } catch (err) {
      handleApiError(err);
    }
  };

  const handleLike = async (id: number) => {
    if (!currentUserId) return;
    // Optimistic update
    mutate((prev) => {
      if (!prev) return prev;
      const toggleLike = (list: TMarketComment[]): TMarketComment[] =>
        list.map((c) => {
          if (c.id === id) {
            return {
              ...c,
              is_liked: !c.is_liked,
              likes_count: c.is_liked ? c.likes_count - 1 : c.likes_count + 1,
            };
          }
          if (c.replies) {
            return { ...c, replies: toggleLike(c.replies) };
          }
          return c;
        });
      return { ...prev, data: toggleLike(prev.data) };
    }, false);

    try {
      await request.post(`/api/user/comments/${id}/like`);
    } catch (err) {
      handleApiError(err);
      mutate();
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await request.delete(`/api/user/comments/${id}`);
      toast.success(t('Comment deleted.'));
      mutate();
    } catch (err) {
      handleApiError(err);
    }
  };

  return (
    <div className="space-y-5">
      {currentUserId && (
        <div className="flex gap-3">
          <CommentAvatar name={auth.user.name} />
          <div className="flex-1 space-y-2">
            <Textarea
              placeholder={t('Share your thoughts…')}
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              className="rounded-xl text-sm dark:bg-secondary"
              rows={3}
            />
            <div className="flex justify-end">
              <Button
                size="sm"
                variant="primary"
                onClick={handlePost}
                disabled={submitting || !newComment.trim()}
              >
                {t('Post Comment')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {isLoading ? (
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="flex gap-3">
              <Skeleton className="size-8 shrink-0 rounded-full" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-4 w-1/4 rounded" />
                <Skeleton className="h-10 w-full rounded" />
              </div>
            </div>
          ))}
        </div>
      ) : comments.length === 0 ? (
        <p className="py-8 text-center text-sm text-black/40 dark:text-white/40">
          {t('No comments yet. Be the first to share your thoughts.')}
        </p>
      ) : (
        <div className="space-y-5">
          {comments.map((comment) => (
            <CommentItem
              key={comment.id}
              comment={comment}
              currentUserId={currentUserId}
              onLike={handleLike}
              onDelete={handleDelete}
              onReplySubmit={handleReplySubmit}
            />
          ))}
        </div>
      )}
    </div>
  );
}
