'use client';

import { useState } from 'react';
import { useImageGeneration } from '../hooks/use-image-generation';
import {
  MODEL_CONFIGS,
  type ModelMode,
  PROVIDERS,
  type ProviderKey,
} from '../lib/provider-config';
import type { Suggestion } from '../lib/suggestions';
import { ImageGeneratorHeader } from './ImageGeneratorHeader';
import { ModelCardCarousel } from './ModelCardCarousel';
import { PromptInput } from './PromptInput';

export function ImageImageGeneratorByProvider({
  suggestions,
  providerKey,
}: {
  suggestions: Suggestion[];
  providerKey: ProviderKey;
}) {
  const {
    images,
    timings,
    failedProviders,
    isLoading,
    startGeneration,
    activePrompt,
  } = useImageGeneration();

  const [showProviders, setShowProviders] = useState(true);
  const [selectedModels, setSelectedModels] = useState<
    Record<ProviderKey, string>
  >(MODEL_CONFIGS.performance);
  const [mode, setMode] = useState<ModelMode>('performance');
  const toggleView = () => {
    setShowProviders((prev) => !prev);
  };

  const handleModeChange = (newMode: ModelMode) => {
    setMode(newMode);
    setSelectedModels(MODEL_CONFIGS[newMode]);
    setShowProviders(true);
  };

  const handleModelChange = (providerKey: ProviderKey, model: string) => {
    setSelectedModels((prev) => ({ ...prev, [providerKey]: model }));
  };

  // Only map the active provider to its selected model
  const providerToModel = {
    [providerKey]: selectedModels[providerKey],
  } as Record<ProviderKey, string>;

  const handlePromptSubmit = (newPrompt: string) => {
    const activeProviders: ProviderKey[] = [providerKey];
    startGeneration(newPrompt, activeProviders, providerToModel);
    setShowProviders(false);
  };

  return (
    <div className="rounded-lg bg-background py-8 px-4 sm:px-6 lg:px-8">
      <div className="mx-auto">
        {/* header */}
        <ImageGeneratorHeader />

        {/* input prompt */}
        <PromptInput
          onSubmit={handlePromptSubmit}
          isLoading={isLoading}
          showProviders={showProviders}
          onToggleProviders={toggleView}
          mode={mode}
          onModeChange={handleModeChange}
          suggestions={suggestions}
        />

        {/* models carousel */}
        {(() => {
          const key = providerKey;
          const provider = PROVIDERS[key];
          if (!provider) return null;

          const imageItem = images.find((img) => img.provider === key);
          const imageData = imageItem?.image;
          const modelId = imageItem?.modelId ?? selectedModels[key] ?? '';
          const timing = timings[key];

          const modelProps = {
            label: provider.displayName,
            models: provider.models,
            value: selectedModels[key],
            providerKey: key,
            onChange: (model: string, pKey: ProviderKey) =>
              handleModelChange(pKey, model),
            iconPath: provider.iconPath,
            color: provider.color,
            enabled: true,
            image: imageData,
            modelId,
            timing,
            failed: failedProviders.includes(key),
          } as const;

          return (
            <>
              <div>
                <ModelCardCarousel models={[modelProps]} />
              </div>
              {activePrompt && activePrompt.length > 0 && (
                <div className="text-center mt-8 text-muted-foreground">
                  {activePrompt}
                </div>
              )}
            </>
          );
        })()}
      </div>
    </div>
  );
}
