'use client';

import { useEffect, useRef, useState } from 'react';

import { useApiClient } from '@/lib/apiClient';

type ViewState = 'form' | 'loading' | 'success' | 'error';

interface PromptsAndTagsResponse {
  prompts: string[];
  tags: string[];
  is_pending_personalization: boolean;
}

const NuxClient = () => {
  const apiClient = useApiClient();
  const [viewState, setViewState] = useState<ViewState>('form');
  const [locale, setLocale] = useState('en-US');
  const [tagsInput, setTagsInput] = useState('');
  const [prompts, setPrompts] = useState<string[]>([]);
  const [tags, setTags] = useState<string[]>([]);
  const [errorMessage, setErrorMessage] = useState('');
  const [elapsedTime, setElapsedTime] = useState(0);
  const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const pollingStartTimeRef = useRef<number | null>(null);

  const clearPolling = () => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
    pollingStartTimeRef.current = null;
  };

  useEffect(() => {
    return () => clearPolling();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setViewState('loading');
    setErrorMessage('');
    setElapsedTime(0);

    const tagsList = tagsInput
      .split(',')
      .map((t) => t.trim())
      .filter((t) => t.length > 0);

    try {
      // Call POST endpoint to trigger generation
      const response = (await apiClient.POST(
        '/api/tags/test/prompts-and-tags' as any,
        {
          body: {
            locale,
            tags: tagsList,
          },
        }
      )) as { data?: { status: string }; error?: { status?: number } };

      if (response.error) {
        const errorMsg =
          response.error.status === 403
            ? 'Access denied: This tool is only available for staff users'
            : `Failed to start generation: ${JSON.stringify(response.error)}`;
        setErrorMessage(errorMsg);
        setViewState('error');
        return;
      }

      // Start polling and elapsed time tracking
      pollingStartTimeRef.current = Date.now();
      startPolling(locale, tagsList);
    } catch (error) {
      setErrorMessage(`Error: ${error}`);
      setViewState('error');
    }
  };

  const startPolling = (localeToCheck: string, tagsToCheck: string[]) => {
    pollingIntervalRef.current = setInterval(async () => {
      // Update elapsed time
      if (pollingStartTimeRef.current) {
        setElapsedTime(
          Math.floor((Date.now() - pollingStartTimeRef.current) / 1000)
        );
      }

      // Check timeout (5 minutes = 300000ms)
      if (
        pollingStartTimeRef.current &&
        Date.now() - pollingStartTimeRef.current > 300000
      ) {
        clearPolling();
        setErrorMessage('Timeout: Prompts not generated after 5 minutes');
        setViewState('error');
        return;
      }

      try {
        const response = (await apiClient.GET(
          '/api/tags/test/prompts-and-tags' as any,
          {
            params: {
              query: {
                locale: localeToCheck,
                tags: tagsToCheck.join(','),
              },
            },
          }
        )) as {
          data?: PromptsAndTagsResponse;
          error?: { status?: number };
        };

        if (response.error) {
          clearPolling();
          const errorMsg =
            response.error.status === 403
              ? 'Access denied: This tool is only available for staff users'
              : `Polling error: ${JSON.stringify(response.error)}`;
          setErrorMessage(errorMsg);
          setViewState('error');
          return;
        }

        if (
          response.data &&
          response.data.prompts.length > 0 &&
          !response.data.is_pending_personalization
        ) {
          clearPolling();
          setPrompts(response.data.prompts);
          setTags(response.data.tags);
          setViewState('success');
        }
      } catch (error) {
        clearPolling();
        setErrorMessage(`Polling error: ${error}`);
        setViewState('error');
      }
    }, 3000);
  };

  const handleReset = () => {
    clearPolling();
    setViewState('form');
    setLocale('en-US');
    setTagsInput('');
    setPrompts([]);
    setTags([]);
    setErrorMessage('');
    setElapsedTime(0);
  };

  return (
    <div
      style={{
        padding: '20px',
        maxWidth: '800px',
        margin: '0 auto',
        height: '100%',
        overflowY: 'auto',
        overflowX: 'hidden',
      }}
    >
      <h1>Staff Testing: Personalized Prompts Generator</h1>
      <p style={{ color: '#666', marginBottom: '20px' }}>
        ⚠️ This tool is only available for staff users. Non-staff users will
        receive a 403 error.
      </p>

      {viewState === 'form' && (
        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: '15px' }}>
            <label
              htmlFor='locale'
              style={{ display: 'block', marginBottom: '5px' }}
            >
              Locale:
            </label>
            <input
              id='locale'
              type='text'
              value={locale}
              onChange={(e) => setLocale(e.target.value)}
              placeholder='e.g., en-US, es-ES, fr-FR'
              style={{
                width: '100%',
                padding: '8px',
                border: '1px solid #ccc',
                borderRadius: '4px',
              }}
              required
            />
          </div>

          <div style={{ marginBottom: '15px' }}>
            <label
              htmlFor='tags'
              style={{ display: 'block', marginBottom: '5px' }}
            >
              Tags (comma-separated):
            </label>
            <input
              id='tags'
              type='text'
              value={tagsInput}
              onChange={(e) => setTagsInput(e.target.value)}
              placeholder='e.g., pop, rock, jazz'
              style={{
                width: '100%',
                padding: '8px',
                border: '1px solid #ccc',
                borderRadius: '4px',
              }}
            />
          </div>

          <button
            type='submit'
            style={{
              padding: '10px 20px',
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
            }}
          >
            Generate Prompts
          </button>
        </form>
      )}

      {viewState === 'loading' && (
        <div>
          <h2>⏳ Generating prompts...</h2>
          <p>Polling every 3 seconds. Will timeout after 5 minutes.</p>
          <p style={{ color: '#666' }}>Elapsed time: {elapsedTime}s</p>
          <button
            onClick={handleReset}
            style={{
              padding: '10px 20px',
              backgroundColor: '#6c757d',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              marginTop: '10px',
            }}
          >
            Cancel
          </button>
        </div>
      )}

      {viewState === 'success' && (
        <div>
          <h2>✅ Success!</h2>
          <div style={{ marginBottom: '20px' }}>
            <h3>Generated Prompts ({prompts.length}):</h3>
            <ul>
              {prompts.map((prompt, idx) => (
                <li key={idx} style={{ marginBottom: '8px' }}>
                  {prompt}
                </li>
              ))}
            </ul>
          </div>

          <div style={{ marginBottom: '20px' }}>
            <h3>Tags ({tags.length}):</h3>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {tags.map((tag, idx) => (
                <span
                  key={idx}
                  style={{
                    padding: '4px 12px',
                    backgroundColor: '#007bff',
                    color: 'white',
                    borderRadius: '16px',
                    fontSize: '14px',
                  }}
                >
                  {tag}
                </span>
              ))}
            </div>
          </div>

          <button
            onClick={handleReset}
            style={{
              padding: '10px 20px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
            }}
          >
            Test Again
          </button>
        </div>
      )}

      {viewState === 'error' && (
        <div>
          <h2>❌ Error</h2>
          <p style={{ color: 'red', marginBottom: '20px' }}>{errorMessage}</p>
          <button
            onClick={handleReset}
            style={{
              padding: '10px 20px',
              backgroundColor: '#dc3545',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
            }}
          >
            Try Again
          </button>
        </div>
      )}
    </div>
  );
};

export default NuxClient;
