"use client";

import { useState } from "react";
import { RecordingState } from "@/lib/useAudioRecorder";
import { uploadToSunoAndGenerateCovers, STYLE_PRESETS } from "@/lib/sunoApi";

interface RecordingControlsProps {
  recordingState: RecordingState;
  recordedAudioUrl: string | null;
  onStartRecording: () => void;
  onStopRecording: () => void;
  onClearRecording: () => void;
  disabled?: boolean;
  isPlaying?: boolean;
  recordedItemsCount?: number; // Optional: for showing "X hits recorded" etc
}

export function RecordingControls({
  recordingState,
  recordedAudioUrl,
  onStartRecording,
  onStopRecording,
  onClearRecording,
  disabled = false,
  isPlaying = false,
  recordedItemsCount,
}: RecordingControlsProps) {
  const [selectedStyle, setSelectedStyle] = useState<string>("relaxing");
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedCovers, setGeneratedCovers] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);

  const handleGenerateCovers = async () => {
    if (!recordedAudioUrl) return;

    setIsGenerating(true);
    setError(null);
    setGeneratedCovers([]);

    try {
      // Fetch the audio blob from the URL
      const response = await fetch(recordedAudioUrl);
      const audioBlob = await response.blob();

      // Get the style string from the preset
      const styleString = STYLE_PRESETS[selectedStyle as keyof typeof STYLE_PRESETS];

      // Upload to Suno and generate covers
      const result = await uploadToSunoAndGenerateCovers(audioBlob, styleString);

      if (result.success && result.data) {
        // Extract audio URLs from the cover_clips array
        const audioUrls = result.data.cover_clips?.map((clip: any) => clip.audio_url).filter(Boolean) || [];
        setGeneratedCovers(audioUrls);
      } else {
        setError(result.error || 'Failed to generate covers');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error occurred');
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <>
      <div className="flex flex-wrap gap-4 items-center justify-center mb-6">
        {recordingState === "idle" && (
          <button
            onClick={onStartRecording}
            disabled={disabled}
            className="px-6 py-3 rounded-lg font-bold bg-red-500 hover:bg-red-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white shadow-lg transition-all"
          >
            ⏺ Record
          </button>
        )}

        {recordingState === "recording" && (
          <button
            onClick={onStopRecording}
            className="px-6 py-3 rounded-lg font-bold bg-red-600 hover:bg-red-700 text-white shadow-lg animate-pulse transition-all"
          >
            ⏹ Stop Recording
          </button>
        )}

        {recordingState === "recorded" && (
          <>
            <button
              onClick={onClearRecording}
              disabled={isPlaying}
              className="px-4 py-3 rounded-lg font-bold bg-gray-700 hover:bg-gray-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white shadow-lg transition-all"
            >
              🗑 Clear
            </button>
            <button
              onClick={onStartRecording}
              disabled={isPlaying}
              className="px-4 py-3 rounded-lg font-bold bg-red-500 hover:bg-red-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white shadow-lg transition-all"
            >
              ⏺ Record New
            </button>
          </>
        )}

        {recordingState === "recording" && (
          <div className="flex items-center gap-2 bg-red-500/20 backdrop-blur-sm px-4 py-2 rounded-lg border border-red-500">
            <div className="w-3 h-3 bg-red-500 rounded-full animate-pulse" />
            <span className="text-white font-mono text-sm">Recording...</span>
          </div>
        )}

        {recordingState === "recorded" && (
          <div className="flex items-center gap-2 bg-green-500/20 backdrop-blur-sm px-4 py-2 rounded-lg border border-green-500">
            <span className="text-white font-mono text-sm">
              ✓ Recording saved
              {recordedItemsCount !== undefined && (
                <> ({recordedItemsCount} {recordedItemsCount === 1 ? 'item' : 'items'})</>
              )}
            </span>
          </div>
        )}
      </div>

      {/* Audio Player - shown when recording is available */}
      {recordingState === "recorded" && recordedAudioUrl && (
        <div className="bg-black/40 backdrop-blur-sm p-4 rounded-2xl shadow-2xl mb-6 w-full max-w-2xl">
          <audio
            controls
            src={recordedAudioUrl}
            className="w-full"
            style={{
              filter: "invert(1) hue-rotate(180deg)",
            }}
          />
        </div>
      )}

      {/* Suno Cover Generation - shown when recording is available */}
      {recordingState === "recorded" && recordedAudioUrl && (
        <div className="bg-black/40 backdrop-blur-sm p-6 rounded-2xl shadow-2xl mb-6 w-full max-w-2xl">
          <h3 className="text-white font-bold text-lg mb-4">🎵 Generate AI Covers with Suno</h3>

          <div className="flex flex-col sm:flex-row gap-4 items-stretch sm:items-center mb-4">
            <div className="flex-1">
              <label htmlFor="style-select" className="block text-white text-sm font-medium mb-2">
                Select Style:
              </label>
              <select
                id="style-select"
                value={selectedStyle}
                onChange={(e) => setSelectedStyle(e.target.value)}
                disabled={isGenerating}
                className="w-full px-4 py-2 rounded-lg bg-gray-800 text-white border border-gray-600 focus:border-purple-500 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {Object.keys(STYLE_PRESETS).map((style) => (
                  <option key={style} value={style}>
                    {style.charAt(0).toUpperCase() + style.slice(1)}
                  </option>
                ))}
              </select>
            </div>

            <button
              onClick={handleGenerateCovers}
              disabled={isGenerating || isPlaying}
              className="px-6 py-2 sm:mt-6 rounded-lg font-bold bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white shadow-lg transition-all whitespace-nowrap"
            >
              {isGenerating ? '⏳ Generating...' : '✨ Generate Covers'}
            </button>
          </div>

          {error && (
            <div className="bg-red-500/20 border border-red-500 rounded-lg p-3 mb-4">
              <p className="text-red-300 text-sm">❌ {error}</p>
            </div>
          )}

          {isGenerating && (
            <div className="flex items-center gap-2 bg-purple-500/20 backdrop-blur-sm px-4 py-3 rounded-lg border border-purple-500 mb-4">
              <div className="w-3 h-3 bg-purple-500 rounded-full animate-pulse" />
              <span className="text-white font-mono text-sm">Generating AI covers... This may take a moment.</span>
            </div>
          )}

          {generatedCovers.length > 0 && (
            <div className="space-y-4">
              <h4 className="text-white font-semibold">Generated Covers:</h4>
              {generatedCovers.map((url, index) => (
                <div key={index} className="bg-gray-800/50 p-3 rounded-lg">
                  <p className="text-white text-sm mb-2">Cover {index + 1}</p>
                  <audio
                    controls
                    src={url}
                    className="w-full"
                    style={{
                      filter: "invert(1) hue-rotate(180deg)",
                    }}
                  />
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </>
  );
}
