import Button from '@/components/Low/Button';
import Modal from '@/components/Modal';
import dynamic from 'next/dynamic';
import React, { useCallback, useState } from 'react';
import { MdAudioFile, MdCloudUpload, MdDelete } from 'react-icons/md';

const Waveform = dynamic(() => import("@/components/Waveform"), { ssr: false });

interface AudioUploadProps {
  isOpen: boolean;
  audioFile: string | undefined;
  setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
  onFileSelect: (file: File | null) => void;
  transcribeAudio: () => void;
  setAudioUrl: React.Dispatch<React.SetStateAction<string | undefined>>;
}

const AudioUpload: React.FC<AudioUploadProps> = ({ isOpen, audioFile, setIsOpen, onFileSelect, transcribeAudio, setAudioUrl }) => {
  const [isDragging, setIsDragging] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDragIn = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragOut = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const validateFile = (file: File): boolean => {
    if (!file.type.startsWith('audio/')) {
      setError('Please upload an audio file');
      return false;
    }
    setError(null);
    return true;
  };

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    setError(null);

    const file = e.dataTransfer.files?.[0];
    if (file && validateFile(file)) {
      onFileSelect(file);
    }
  }, [onFileSelect]);

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file && validateFile(file)) {
      onFileSelect(file);
    }
  };

  const handleRemoveAudio = () => {
    onFileSelect(null);
  };

  return (
    <Modal isOpen={isOpen} onClose={() => setIsOpen(false)}>
      <div className="w-full space-y-4">
        {!audioFile && (
          <div
            className={`relative border-2 border-dashed rounded-lg p-8 text-center 
              ${isDragging
                ? 'border-blue-500 bg-blue-50'
                : 'border-gray-300 hover:border-gray-400'
              } 
              transition-all duration-200 ease-in-out`}
            onDragEnter={handleDragIn}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
          >
            <input
              type="file"
              accept="audio/*"
              onChange={handleFileUpload}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
              title="Choose audio file"
            />
            <div className="space-y-4">
              <div className="flex justify-center">
                {error ? (
                  <MdAudioFile className="w-16 h-16 text-red-500" />
                ) : (
                  <MdCloudUpload className="w-16 h-16 text-gray-400" />
                )}
              </div>
              <div className="space-y-2">
                <h3 className="text-lg font-medium text-gray-700">
                  {error ? error : 'Upload Audio File'}
                </h3>
                <p className="text-sm text-gray-500">
                  Drag and drop your audio file here, or click to select
                </p>
              </div>
            </div>
          </div>
        )}

        {audioFile && (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="text-lg font-medium text-gray-700">Audio Upload</h3>
              <button
                onClick={handleRemoveAudio}
                className="flex items-center gap-2 px-3 py-1.5 text-sm text-white bg-red-500 hover:bg-red-600 rounded-md transition-colors duration-200 w-36"
              >
                <MdDelete className="w-4 h-4" />
                Remove Audio
              </button>
            </div>
            <Waveform
              variant='edit'
              audio={audioFile}
              waveColor="#ddd"
              progressColor="#4a90e2"
              setAudioUrl={setAudioUrl}
            />
            <div className="flex w-full justify-between pt-8">
              <Button color="purple" onClick={() => setIsOpen(false)} variant="outline" className="max-w-[200px] self-end w-full">
                Cancel
              </Button>
              <Button color="purple" onClick={()=> { transcribeAudio(); setIsOpen(false);}} className="max-w-[200px] self-end w-full">
                Upload
              </Button>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

export default AudioUpload;