import React, { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { FileUpload } from '../ui/input';
import {
  Wand2,
  Mic2,
  Layers,
  Music,
  Activity,
  Download,
  Play,
  CheckCircle,
} from 'lucide-react';
import { useToast } from '../../context/ToastContext';
import { UploadProgressBar } from '../upload/UploadProgressBar';

type ToolType = 'stem-splitter' | 'vocal-remover' | 'key-bpm' | 'mastering';

export const AIToolsView: React.FC = () => {
  const { addToast } = useToast();
  const [activeTool, setActiveTool] = useState<ToolType>('stem-splitter');
  const [isProcessing, setIsProcessing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [result, setResult] = useState<any>(null);

  const tools = [
    {
      id: 'stem-splitter',
      label: 'Stem Splitter',
      icon: <Layers className="w-4 h-4" />,
      desc: 'Separate tracks into 4 stems: Drums, Bass, Vocals, Other.',
    },
    {
      id: 'vocal-remover',
      label: 'Vocal Remover',
      icon: <Mic2 className="w-4 h-4" />,
      desc: 'Extract acapellas or create instrumentals instantly.',
    },
    {
      id: 'key-bpm',
      label: 'Key & BPM',
      icon: <Activity className="w-4 h-4" />,
      desc: 'Detect the tempo and musical key of any audio file.',
    },
    {
      id: 'mastering',
      label: 'AI Mastering',
      icon: <Wand2 className="w-4 h-4" />,
      desc: 'Instant professional mastering for your mixes.',
    },
  ];

  const handleUpload = (files: FileList) => {
    setIsProcessing(true);
    setProgress(0);
    setResult(null);

    // Simulate Processing
    let p = 0;
    const interval = setInterval(() => {
      p += 5;
      setProgress(p);
      if (p >= 100) {
        clearInterval(interval);
        setIsProcessing(false);
        addToast('Processing complete!', 'success');
        // Mock Result
        setResult({
          fileName: files[0].name,
          outputs:
            activeTool === 'stem-splitter'
              ? ['Drums.wav', 'Bass.wav', 'Vocals.wav', 'Other.wav']
              : ['Instrumental.wav', 'Acapella.wav'],
        });
      }
    }, 100);
  };

  return (
    <div className="h-full flex flex-col gap-6 animate-fadeIn">
      {/* Tool Selection */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {tools.map((tool) => (
          <button
            key={tool.id}
            onClick={() => {
              setActiveTool(tool.id as ToolType);
              setResult(null);
            }}
            className={`p-4 rounded-xl border text-left transition-all group ${activeTool === tool.id ? 'bg-kodo-cyan/10 border-kodo-cyan' : 'bg-kodo-graphite border-kodo-steel hover:bg-white/5'}`}
          >
            <div
              className={`w-10 h-10 rounded-lg flex items-center justify-center mb-3 ${activeTool === tool.id ? 'bg-kodo-cyan text-black' : 'bg-kodo-ink text-gray-400 group-hover:text-white'}`}
            >
              {tool.icon}
            </div>
            <div
              className={`font-bold text-sm ${activeTool === tool.id ? 'text-white' : 'text-gray-300'}`}
            >
              {tool.label}
            </div>
            <div className="text-[10px] text-gray-500 mt-1 leading-tight">
              {tool.desc}
            </div>
          </button>
        ))}
      </div>

      {/* Workspace */}
      <Card
        variant="default"
        className="flex-1 flex flex-col justify-center items-center min-h-[400px]"
      >
        {!isProcessing && !result && (
          <div className="w-full max-w-md">
            <FileUpload onUpload={handleUpload} />
            <p className="text-center text-xs text-gray-500 mt-4">
              Supported formats: WAV, MP3, FLAC, AIFF. Max 100MB.
            </p>
          </div>
        )}

        {isProcessing && (
          <div className="w-full max-w-md text-center space-y-4">
            <div className="w-20 h-20 bg-kodo-ink rounded-full border-4 border-kodo-steel border-t-kodo-cyan animate-spin mx-auto"></div>
            <h3 className="text-xl font-bold text-white animate-pulse">
              Processing Audio...
            </h3>
            <p className="text-gray-400 text-sm">
              Separating frequencies and analyzing waveforms.
            </p>
            <UploadProgressBar progress={progress} status="processing" />
          </div>
        )}

        {result && (
          <div className="w-full max-w-2xl animate-scaleIn">
            <div className="flex items-center gap-4 mb-6 p-4 bg-kodo-lime/10 border border-kodo-lime/30 rounded-lg">
              <CheckCircle className="w-6 h-6 text-kodo-lime" />
              <div>
                <h3 className="font-bold text-white">Analysis Complete</h3>
                <p className="text-xs text-gray-300">{result.fileName}</p>
              </div>
              <Button
                variant="ghost"
                size="sm"
                className="ml-auto"
                onClick={() => setResult(null)}
              >
                Reset
              </Button>
            </div>

            <h4 className="text-sm font-bold text-gray-400 uppercase mb-4 tracking-wider">
              Output Files
            </h4>
            <div className="grid grid-cols-1 gap-3">
              {result.outputs.map((file: string, i: number) => (
                <div
                  key={i}
                  className="flex items-center justify-between p-3 bg-kodo-ink rounded border border-kodo-steel hover:border-kodo-cyan/50 transition-colors"
                >
                  <div className="flex items-center gap-3">
                    <Music className="w-5 h-5 text-kodo-cyan" />
                    <span className="text-white font-medium">{file}</span>
                  </div>
                  <div className="flex gap-2">
                    <Button variant="ghost" size="icon">
                      <Play className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="secondary"
                      size="sm"
                      icon={<Download className="w-4 h-4" />}
                    >
                      Download
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </Card>
    </div>
  );
};
