'use client';

import { useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import SongList from '@/components/song/Songlist';
import { useApiClient } from '@/lib/apiClient';
import { ContextType } from '@/logging/contextTypes';
import { Clip } from '@/state/clipStore';

type Result = Clip & {
  lyrics: string;
  username?: string;
};

export default function IsThisUsClient() {
  const { clips } = useStores();
  const [lyrics, setLyrics] = useState('');
  const [date, setDate] = useState(new Date().toISOString());
  const [results, setResults] = useState<Result[] | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notApplicable, setNotApplicable] = useState(false);

  const apiClient = useApiClient();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const { data, error } = await apiClient.POST('/api/search/is_this_us', {
        body: {
          lyrics: lyrics,
          created_before: notApplicable ? null : date,
        },
      });

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

      // Transform the API response to match the Clip type
      const transformedResults = data.map((result: any) => ({
        ...result,
        metadata: result.metadata || {},
        major_model_version: result.major_model_version || '',
        model_name: result.model_name || '',
        is_liked: result.is_liked || false,
        is_handle_updated: result.is_handle_updated || false,
        is_trashed: result.is_trashed || false,
        entity_type: result.entity_type || 'song_schema',
      }));
      setResults(transformedResults);
      clips.updateClips(transformedResults);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className='flex h-screen w-full flex-col p-6'>
      <form onSubmit={handleSubmit} className='flex flex-col gap-4'>
        <div className='flex w-full flex-col justify-between gap-4 md:flex-row'>
          <div className='w-full grow md:w-3/4'>
            <textarea
              value={lyrics}
              onChange={(e) => setLyrics(e.target.value)}
              placeholder='Enter lyrics...'
              className='h-full min-h-[100px] w-full rounded-md border border-gray-300 p-2'
              required
            />
          </div>
          <div className='flex w-full flex-col md:w-1/4'>
            <label
              htmlFor='createdBefore'
              className='mb-1 self-start text-sm font-medium'
            >
              Created Before
            </label>
            <input
              id='createdBefore'
              type='datetime-local'
              value={date.slice(0, 16)}
              onChange={(e) =>
                setDate(
                  e.target.value ? new Date(e.target.value).toISOString() : ''
                )
              }
              className={`mb-2 w-full rounded-md border border-gray-300 p-2 ${notApplicable ? 'bg-gray-200 text-gray-500' : ''}`}
              disabled={notApplicable}
            />
            <div className='mt-1 flex items-center'>
              <input
                type='checkbox'
                id='notApplicable'
                checked={notApplicable}
                onChange={(e) => {
                  setNotApplicable(e.target.checked);
                  if (e.target.checked) {
                    setDate('');
                  }
                }}
                className='mr-2'
              />
              <label htmlFor='notApplicable' className='text-sm'>
                Not applicable
              </label>
            </div>
          </div>
        </div>
        <div className='mt-4 flex justify-center'>
          <button
            type='submit'
            disabled={isLoading}
            className='rounded-md bg-blue-500 px-6 py-2 text-white hover:bg-blue-600 disabled:bg-blue-300'
          >
            {isLoading ? 'Loading...' : 'Is This Us'}
          </button>
        </div>
      </form>

      {error && (
        <div className='mb-4 text-center text-accent-error-on-primary'>
          {error}
        </div>
      )}

      {results && (
        <SongList
          songs={results}
          playlistId='is_this_us_results'
          contextId='is_this_us_results'
          contextType={ContextType.BSide}
          isLoading={isLoading}
          songRowProps={{
            showStats: true,
            showTags: true,
            showActions: true,
            showUser: true,
            trendingMode: true,
          }}
        />
      )}
    </div>
  );
}
