'use client';

import { useState } from 'react';

import { toast } from '@/components/toast/Toast';
import { useApiClient } from '@/lib/apiClient';

type QueryType = 'handle' | 'email' | 'phone_number';

const UserActivityClient = () => {
  interface UserCommentActivity {
    results: Array<{
      user_id: string;
      user_handle: string;
      content: string;
      created_at: string;
      clip_id?: string | null;
    }>;
    total_count?: number;
    next_cursor?: string | null;
  }

  const BACKEND_PAGE_SIZE = 25;
  const apiClient = useApiClient();
  const [queryValue, setQueryValue] = useState('');
  const [queryType, setQueryType] = useState<
    'handle' | 'email' | 'phone_number'
  >('handle');
  const [userCommentResults, setUserCommentResults] =
    useState<UserCommentActivity | null>(null);
  const [userLoading, setUserLoading] = useState(false);
  const [userError, setUserError] = useState<string | null>(null);
  const [userCommentCount, setUserCommentCount] = useState<number | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [cursors, setCursors] = useState<(string | null)[]>([null]);

  const loadNextPage = async () => {
    if (userCommentResults?.next_cursor) {
      try {
        const nextCursor = userCommentResults.next_cursor;
        await searchUserComments(nextCursor);
        // Only update state after successful API call
        const newCursors = [...cursors, nextCursor];
        setCursors(newCursors);
        setCurrentPage(currentPage + 1);
      } catch (err) {
        // API call failed, pagination state remains unchanged
        console.error('Failed to load next page:', err);
      }
    }
  };

  const loadPreviousPage = async () => {
    if (currentPage > 1) {
      const newPage = currentPage - 1;
      const previousCursor = cursors[newPage - 1];
      try {
        await searchUserComments(previousCursor);
        // Only update state after successful API call
        setCurrentPage(newPage);
        setCursors(cursors.slice(0, newPage));
      } catch (err) {
        // API call failed, pagination state remains unchanged
        console.error('Failed to load previous page:', err);
      }
    }
  };

  const hasNextPage = () => {
    return !!userCommentResults?.next_cursor;
  };

  const hasPreviousPage = () => {
    return currentPage > 1;
  };

  const handleUserSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1);
    setCursors([null]);

    await searchUserComments();
  };

  const searchUserComments = async (cursor?: string | null) => {
    if (!queryValue.trim()) {
      setUserError('Please enter a value to query');
      setUserCommentResults(null); // Clear previous results
      return;
    }

    setUserLoading(true);
    setUserError(null);
    if (!cursor) {
      setUserCommentResults(null); // Clear previous results when starting new search
    }

    try {
      const { data, error } = await apiClient.GET(
        '/api/comment/user/{identifier}',
        {
          params: {
            query: {
              id_type: queryType,
              cursor: cursor || undefined,
              page_size: BACKEND_PAGE_SIZE,
            },
            path: {
              identifier: queryValue,
            },
          },
        }
      );

      if (error) {
        throw new Error('Failed to fetch user comments');
      }

      // Always replace results - no accumulation needed with cursor pagination
      setUserCommentResults(data as UserCommentActivity);
      setUserCommentCount(data.total_count || 0);
    } catch (err) {
      setUserError(err instanceof Error ? err.message : 'Something went wrong');
    } finally {
      setUserLoading(false);
    }
  };

  const handleDeleteComments = async () => {
    setUserLoading(true);
    // check query type and value are not empty
    if (!queryValue.trim() || !queryType) {
      setUserError('Please enter user information to delete comments');
      return;
    }

    try {
      const { error } = await apiClient.DELETE(
        '/api/comment/user/{identifier}',
        {
          params: {
            query: {
              id_type: queryType,
            },
            path: {
              identifier: queryValue,
            },
          },
        }
      );

      if (error) {
        throw new Error('Failed to delete comments');
      }

      toast({
        title: 'Success',
        description: 'All comments deleted successfully',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });

      //refetch comment results
      setCursors([null]);
      setCurrentPage(1);
      await searchUserComments();
    } catch (err) {
      toast({
        title: 'Error',
        description:
          err instanceof Error ? err.message : 'Failed to delete comments',
        status: 'error',
        duration: 3000,
        isClosable: true,
      });
    } finally {
      setUserLoading(false);
    }
  };

  return (
    <div className='w-full overflow-y-auto bg-gray-100 pb-40'>
      {/* Single User Check Section */}
      <div className='rounded-lg border border-gray-300 bg-gray-50 p-6 shadow-sm'>
        <h2 className='mb-4 text-xl font-semibold text-gray-900'>
          Check User Activity for Spam
        </h2>
        <form onSubmit={handleUserSubmit} className='mb-6 flex flex-col gap-4'>
          <div className='flex flex-col gap-4 md:flex-row'>
            <div className='flex flex-col gap-2 md:w-1/4'>
              <label className='text-sm font-medium'>Query Type</label>
              <select
                value={queryType}
                onChange={(e) => setQueryType(e.target.value as QueryType)}
                className='rounded-md border border-gray-300 p-2'
              >
                <option value='handle'>Handle</option>
                <option value='email'>Email</option>
                <option value='phone_number'>Phone Number</option>
              </select>
            </div>
            <div className='flex flex-col gap-2 md:w-3/4'>
              <label className='text-sm font-medium'>
                {queryType === 'handle'
                  ? 'Handle'
                  : queryType === 'email'
                    ? 'Email'
                    : 'Phone Number'}
              </label>
              <input
                type={queryType === 'email' ? 'email' : 'text'}
                value={queryValue}
                onChange={(e) => setQueryValue(e.target.value)}
                placeholder={`Enter ${queryType}...`}
                className='rounded-md border border-gray-300 p-2'
                required
              />
            </div>
          </div>
          <div className='flex justify-center'>
            <button
              type='submit'
              disabled={userLoading}
              className='rounded-md bg-blue-500 px-6 py-2 text-white hover:bg-blue-600 disabled:bg-blue-300'
            >
              {userLoading ? 'Loading...' : 'Check User Activity'}
            </button>
          </div>
        </form>

        {userError && (
          <div className='mb-4 rounded-md bg-red-50 p-4 text-center text-red-500'>
            {userError}
          </div>
        )}

        {userCommentResults && (
          <div className='rounded-lg border border-gray-300 bg-gray-50 p-6 shadow-sm'>
            <h3 className='mb-4 text-lg font-semibold text-gray-900'>
              Recent Comment Activity
            </h3>
            <div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
              <div>
                <p className='text-sm text-gray-600'>Total Comments</p>
                <p className='font-medium text-gray-900'>
                  {userCommentCount || 0}
                </p>
              </div>
              <div className='col-span-full'>
                <p className='mb-4 text-sm text-gray-600'>Clip Comments</p>
                {userCommentResults.results.length > 0 ? (
                  <div className='overflow-x-auto'>
                    <table className='min-w-full divide-y divide-gray-200 rounded-lg shadow-sm'>
                      <thead className='bg-gray-50'>
                        <tr>
                          <th className='px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase'>
                            Date
                          </th>
                          <th className='px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase'>
                            Time
                          </th>
                          <th className='px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase'>
                            Clip ID
                          </th>
                          <th className='px-6 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase'>
                            Comment
                          </th>
                        </tr>
                      </thead>
                      <tbody className='divide-y divide-gray-200'>
                        {userCommentResults.results.map((result, index) => (
                          <tr
                            key={index}
                            className='hover:bg-gray-100'
                            onClick={() => {
                              if (result.clip_id) {
                                window.open(
                                  `/song/${result.clip_id}`,
                                  '_blank'
                                );
                              }
                            }}
                          >
                            <td className='px-6 py-4 text-sm whitespace-nowrap text-gray-900'>
                              {new Date(result.created_at).toLocaleDateString()}
                            </td>
                            <td className='px-6 py-4 text-sm whitespace-nowrap text-gray-900'>
                              {new Date(result.created_at).toLocaleTimeString()}
                            </td>
                            <td className='max-w-md px-6 py-4 text-sm text-gray-900'>
                              {result.clip_id || 'N/A'}
                            </td>
                            <td className='max-w-md px-6 py-4 text-sm text-gray-900'>
                              <div className='truncate' title={result.content}>
                                {result.content}
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div className='py-8 text-center text-gray-500'>
                    No comments found
                  </div>
                )}
              </div>
            </div>
            {userCommentResults.results.length > 0 && (
              <div className='mt-6 flex items-center justify-between border-t border-gray-200 px-6 py-3'>
                <div className='flex flex-1 justify-between sm:hidden'>
                  <button
                    onClick={loadPreviousPage}
                    disabled={!hasPreviousPage()}
                    className='relative inline-flex items-center rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 disabled:bg-gray-100 disabled:text-gray-400'
                  >
                    Previous
                  </button>
                  <button
                    onClick={loadNextPage}
                    disabled={!hasNextPage()}
                    className='relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 disabled:bg-gray-100 disabled:text-gray-400'
                  >
                    Next
                  </button>
                </div>
                <div className='hidden sm:flex sm:flex-1 sm:items-center sm:justify-between'>
                  <div>
                    <p className='text-sm text-gray-700'>
                      Showing{' '}
                      <span className='font-medium'>
                        {(currentPage - 1) * BACKEND_PAGE_SIZE + 1}
                      </span>{' '}
                      to{' '}
                      <span className='font-medium'>
                        {(currentPage - 1) * BACKEND_PAGE_SIZE +
                          (userCommentResults?.results.length || 0)}
                      </span>{' '}
                      of <span className='font-medium'>{userCommentCount}</span>{' '}
                      results
                    </p>
                  </div>
                  <div>
                    <nav
                      className='isolate inline-flex -space-x-px rounded-md shadow-sm'
                      aria-label='Pagination'
                    >
                      <button
                        onClick={loadPreviousPage}
                        disabled={!hasPreviousPage()}
                        className='relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-gray-300 ring-inset hover:bg-gray-200 focus:z-20 focus:outline-offset-0 disabled:bg-gray-100'
                      >
                        <span className='sr-only'>Previous</span>‹
                      </button>
                      <span className='relative z-10 inline-flex items-center bg-blue-600 px-4 py-2 text-sm font-semibold text-white focus:z-20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600'>
                        {currentPage}
                      </span>
                      <button
                        onClick={loadNextPage}
                        disabled={!hasNextPage()}
                        className='relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-gray-300 ring-inset hover:bg-gray-200 focus:z-20 focus:outline-offset-0 disabled:bg-gray-100'
                      >
                        <span className='sr-only'>Next</span>›
                      </button>
                    </nav>
                  </div>
                </div>
              </div>
            )}
            <div className='mt-4 flex justify-center'>
              <button
                onClick={() => {
                  if (
                    window.confirm(
                      'Are you sure you want to delete all comments? This action cannot be undone.'
                    )
                  ) {
                    handleDeleteComments();
                  }
                }}
                className='rounded-md bg-red-500 px-6 py-2 text-white hover:bg-red-600 disabled:bg-red-300'
              >
                Delete All Comments
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default UserActivityClient;
