'use client';

import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { useRouter } from 'next/navigation';
import React, { useCallback, useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { ClockIcon, TrashIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';

interface WatchHistoryResponse {
  success: boolean;
  hook_ids: string[];
  count: number;
  message?: string;
}

interface ResetResponse {
  success: boolean;
  message: string;
}

const WatchHistoryClient: React.FC = observer(() => {
  const { session } = useStores();
  const router = useRouter();
  const apiClient = useApiClient();

  const [isLoading, setIsLoading] = useState(true);
  const [watchHistory, setWatchHistory] = useState<string[]>([]);
  const [historyCount, setHistoryCount] = useState(0);
  const [confirmReset, setConfirmReset] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [showFullList, setShowFullList] = useState(false);

  // Check if user is staff after session loads
  useEffect(() => {
    if (session.sessionIsLoaded && !session.isStaff) {
      router.push('/hooks');
    }
  }, [session.sessionIsLoaded, session.isStaff, router]);

  // Fetch watch history on mount
  const fetchWatchHistory = useCallback(async () => {
    setIsLoading(true);
    try {
      const { data, error } = await apiClient.GET(
        '/api/video/hooks/admin/watch_history/inspect'
      );

      if (error) {
        router.push('/hooks');
        return;
      }

      const typed = data as WatchHistoryResponse;

      if (typed.success) {
        setWatchHistory(typed.hook_ids || []);
        setHistoryCount(typed.count || 0);

        // Message already shown in UI if needed
        // Don't show success toast for loading - page already shows the data
      }
    } catch (error) {
      console.error('Error fetching watch history:', error);
      // Error is handled by UI state
    } finally {
      setIsLoading(false);
    }
  }, [apiClient, router]);

  // Fetch watch history on component mount
  useEffect(() => {
    fetchWatchHistory();
  }, [fetchWatchHistory]);

  // Handle reset watch history
  const handleResetWatchHistory = useCallback(async () => {
    if (!confirmReset) {
      return; // Confirmation checkbox prevents this
    }

    setIsResetting(true);
    try {
      const { data, error } = await apiClient.POST(
        '/api/video/hooks/admin/watch_history/reset',
        {
          body: {
            confirm: true,
          },
        }
      );

      if (error) {
        router.push('/hooks');
        return;
      }

      const typed = data as ResetResponse;

      if (typed.success) {
        // Clear the local state
        setWatchHistory([]);
        setHistoryCount(0);
        setConfirmReset(false);

        // Refetch to confirm it's cleared
        setTimeout(() => {
          fetchWatchHistory();
        }, 1000);
      }
    } catch (error) {
      console.error('Error resetting watch history:', error);
      // Error is handled by UI state
    } finally {
      setIsResetting(false);
    }
  }, [confirmReset, apiClient, fetchWatchHistory, router]);

  // Navigate to hook
  const handleNavigateToHook = useCallback((hookId: string) => {
    window.open(`/hook/${hookId}`, '_blank');
  }, []);

  // Don't render until session is loaded
  if (!session.sessionIsLoaded) {
    return (
      <div className='flex h-full w-full items-center justify-center'>
        <SpinnerSVG className='h-8 w-8' />
      </div>
    );
  }

  if (!session.isStaff) {
    return null;
  }

  const displayLimit = showFullList ? watchHistory.length : 20;
  const displayedHistory = watchHistory.slice(0, displayLimit);
  const hasMore = watchHistory.length > 20;

  return (
    <div className='flex h-full w-full flex-col bg-background-primary p-8'>
      <div className='mx-auto w-full max-w-4xl'>
        {/* Header */}
        <div className='mb-8'>
          <h2 className='text-xl font-semibold text-foreground-primary'>
            Manage your Hooks watch history
          </h2>
        </div>

        {/* Stats Card */}
        <div className='mb-8 rounded-2xl bg-background-glass-thin p-6'>
          <div className='flex items-center justify-between'>
            <div className='flex items-center gap-3'>
              <div>
                <p className='text-sm text-foreground-secondary'>
                  Total Watched Hooks
                </p>
                <p className='text-2xl font-bold text-foreground-primary'>
                  {isLoading ? '—' : historyCount}
                </p>
              </div>
            </div>
            <Button
              onClick={fetchWatchHistory}
              disabled={isLoading}
              variant={ButtonVariant.Secondary}
              size={ButtonSize.Small}
              shape={ButtonShape.Pill}
            >
              Refresh
            </Button>
          </div>
        </div>

        {/* Reset Section */}
        <div className='mb-8 rounded-2xl bg-background-glass-thin p-6'>
          <h2 className='mb-4 text-xl font-semibold text-foreground-primary'>
            Reset Watch History
          </h2>

          <div className='space-y-4'>
            <p className='text-sm text-foreground-secondary'>
              This action will permanently delete all {historyCount} items from
              your watch history. This cannot be undone.
            </p>

            {watchHistory.length > 0 && (
              <div className='flex items-center gap-3'>
                <input
                  type='checkbox'
                  id='confirmReset'
                  checked={confirmReset}
                  onChange={(e) => setConfirmReset(e.target.checked)}
                  className='text-accent-primary focus:ring-accent-primary h-4 w-4 rounded border-border-primary bg-background-glass-thin focus:ring-2'
                />
                <label
                  htmlFor='confirmReset'
                  className='cursor-pointer text-sm text-foreground-primary select-none'
                >
                  I understand this will permanently delete my watch history
                </label>
              </div>
            )}

            <Button
              onClick={handleResetWatchHistory}
              disabled={
                watchHistory.length === 0 || !confirmReset || isResetting
              }
              variant={ButtonVariant.Standard}
              size={ButtonSize.Medium}
              shape={ButtonShape.Pill}
              className={clsx(
                'w-full',
                confirmReset && watchHistory.length > 0
                  ? 'bg-accent-error text-accent-error-contrast hover:bg-accent-error/90'
                  : ''
              )}
              icon={isResetting ? undefined : TrashIcon}
            >
              {isResetting ? (
                <span className='flex items-center justify-center gap-2'>
                  <SpinnerSVG className='h-4 w-4' />
                  Resetting...
                </span>
              ) : (
                'Reset Watch History'
              )}
            </Button>
          </div>
        </div>

        {/* Watch History Table */}
        <div className='mb-8 rounded-2xl bg-background-glass-thin p-6'>
          <h2 className='mb-4 text-xl font-semibold text-foreground-primary'>
            Watch History
          </h2>

          {isLoading ? (
            <div className='flex items-center justify-center py-12'>
              <SpinnerSVG className='h-8 w-8' />
            </div>
          ) : watchHistory.length === 0 ? (
            <div className='py-12 text-center text-foreground-secondary'>
              <ClockIcon className='mx-auto mb-4 h-12 w-12 opacity-50' />
              <p>No watch history found</p>
            </div>
          ) : (
            <>
              <div className='overflow-hidden rounded-lg border border-border-primary'>
                <table className='w-full'>
                  <thead className='bg-background-glass-thin'>
                    <tr>
                      <th className='px-4 py-3 text-left text-sm font-medium text-foreground-secondary'>
                        #
                      </th>
                      <th className='px-4 py-3 text-left text-sm font-medium text-foreground-secondary'>
                        Hook ID
                      </th>
                    </tr>
                  </thead>
                  <tbody className='divide-y divide-border-primary'>
                    {displayedHistory.map((hookId, index) => (
                      <tr
                        key={`${hookId}-${index}`}
                        className='transition-colors hover:bg-background-glass-thin'
                      >
                        <td className='px-4 py-3 text-sm text-foreground-secondary'>
                          {index + 1}
                        </td>
                        <td className='px-4 py-3'>
                          <button
                            onClick={() => handleNavigateToHook(hookId)}
                            className='hover:text-accent-primary text-left transition-colors'
                          >
                            <code className='hover:text-accent-primary font-mono text-sm text-foreground-primary'>
                              {hookId}
                            </code>
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {hasMore && (
                <div className='mt-4 text-center'>
                  <Button
                    onClick={() => setShowFullList(!showFullList)}
                    variant={ButtonVariant.Secondary}
                    size={ButtonSize.Small}
                    shape={ButtonShape.Pill}
                  >
                    {showFullList
                      ? 'Show Less'
                      : `Show All (${watchHistory.length - 20} more)`}
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
});

export default WatchHistoryClient;
