import React, { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { WaveformVisualizer } from '../../ui/WaveformVisualizer';
import { MetadataForm, TrackMetadata } from './MetadataForm';
import { UploadFile } from '../FilePreviewCard';
import {
  Play,
  Pause,
  Save,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { useToast } from '../../../context/ToastContext';

interface MetadataEditorProps {
  files: UploadFile[];
  onBack: () => void;
  onNext: (metadata: Record<string, TrackMetadata>) => void;
}

export const MetadataEditor: React.FC<MetadataEditorProps> = ({
  files,
  onBack,
  onNext,
}) => {
  const { addToast } = useToast();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);

  // Store metadata for all files
  const [allMetadata, setAllMetadata] = useState<Record<string, TrackMetadata>>(
    {},
  );

  const currentFile = files[currentIndex];

  // Initialize metadata store
  useEffect(() => {
    const initial: Record<string, TrackMetadata> = {};
    files.forEach((f) => {
      if (!allMetadata[f.id]) {
        initial[f.id] = {
          title: f.file.name.replace(/\.[^/.]+$/, ''),
          artist: '',
          album: '',
          genre: '',
          bpm: '',
          key: '',
          releaseDate: new Date().toISOString().split('T')[0],
          isrc: '',
          label: '',
          copyright: '',
          description: '',
          tags: [],
          lyrics: '',
          coverArtUrl: undefined,
        };
      }
    });
    if (Object.keys(initial).length > 0) {
      setAllMetadata((prev) => ({ ...prev, ...initial }));
    }
  }, [files]);

  // Mock Playback
  useEffect(() => {
    let interval: any;
    if (isPlaying) {
      interval = setInterval(() => {
        setProgress((p) => (p >= 100 ? 0 : p + 0.5));
      }, 100);
    }
    return () => clearInterval(interval);
  }, [isPlaying]);

  if (!currentFile) return null;

  const handleMetadataChange = (data: Partial<TrackMetadata>) => {
    setAllMetadata((prev) => ({
      ...prev,
      [currentFile.id]: { ...prev[currentFile.id], ...data },
    }));
  };

  const handleNextTrack = () => {
    if (currentIndex < files.length - 1) {
      setCurrentIndex(currentIndex + 1);
      setProgress(0);
      setIsPlaying(false);
    }
  };

  const handlePrevTrack = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
      setProgress(0);
      setIsPlaying(false);
    }
  };

  const handlePublish = () => {
    // Validate
    const incomplete = files.find(
      (f) => !allMetadata[f.id]?.title || !allMetadata[f.id]?.artist,
    );
    if (incomplete) {
      addToast(
        `Please fill required fields for ${incomplete.file.name}`,
        'error',
      );
      // Navigate to incomplete track
      const idx = files.findIndex((f) => f.id === incomplete.id);
      setCurrentIndex(idx);
      return;
    }
    onNext(allMetadata);
  };

  const currentMeta =
    allMetadata[currentFile.id] || ({} as Partial<TrackMetadata>);

  return (
    <div className="flex flex-col gap-6 animate-fadeIn">
      {/* Editor Header / Player */}
      <Card
        variant="gaming"
        className="sticky top-20 z-30 shadow-2xl border-kodo-cyan/20"
      >
        <div className="flex items-center gap-4 mb-4">
          <div className="flex gap-4 items-center flex-1">
            <button
              onClick={() => setIsPlaying(!isPlaying)}
              className="w-12 h-12 rounded-full bg-kodo-cyan text-black flex items-center justify-center hover:scale-105 transition-transform"
            >
              {isPlaying ? (
                <Pause className="w-5 h-5 fill-current" />
              ) : (
                <Play className="w-5 h-5 fill-current ml-1" />
              )}
            </button>
            <div>
              <h3 className="font-bold text-white text-lg">
                {currentMeta.title || currentFile.file.name}
              </h3>
              <p className="text-xs text-gray-400 font-mono">
                {currentMeta.artist || 'Unknown Artist'} • {currentIndex + 1} of{' '}
                {files.length}
              </p>
            </div>
          </div>

          <div className="flex gap-2">
            <Button
              variant="ghost"
              onClick={handlePrevTrack}
              disabled={currentIndex === 0}
            >
              <ChevronLeft className="w-5 h-5" />
            </Button>
            <Button
              variant="ghost"
              onClick={handleNextTrack}
              disabled={currentIndex === files.length - 1}
            >
              <ChevronRight className="w-5 h-5" />
            </Button>
          </div>
        </div>

        <div className="bg-black/20 rounded-lg p-2 border border-white/5">
          <WaveformVisualizer
            progress={progress}
            onSeek={setProgress}
            height={48}
            color="#374054"
            playedColor="#66FCF1"
          />
        </div>
      </Card>

      {/* Form Area */}
      <Card variant="default">
        <MetadataForm
          initialData={currentMeta}
          onChange={handleMetadataChange}
          fileName={currentFile.file.name}
        />
      </Card>

      {/* Action Bar */}
      <div className="flex justify-between items-center p-4 bg-kodo-ink rounded-xl border border-kodo-steel sticky bottom-4 z-30 shadow-2xl">
        <Button variant="ghost" onClick={onBack}>
          Back to Upload
        </Button>
        <div className="flex gap-3">
          <Button
            variant="secondary"
            icon={<Save className="w-4 h-4" />}
            onClick={() => addToast('Draft Saved', 'success')}
          >
            Save Draft
          </Button>
          <Button
            variant="primary"
            icon={<CheckCircle className="w-4 h-4" />}
            onClick={handlePublish}
          >
            Review & Publish
          </Button>
        </div>
      </div>
    </div>
  );
};
