import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Camera, Music, Hash, FileText, Check } from 'lucide-react';
import { CoverArtUploadModal } from './CoverArtUploadModal';
import { LyricsEditorModal } from './LyricsEditorModal';
import { TagSuggestionsModal } from './TagSuggestionsModal';

export interface TrackMetadata {
  title: string;
  artist: string;
  album: string;
  genre: string;
  bpm: string;
  key: string;
  releaseDate: string;
  isrc: string;
  label: string;
  copyright: string;
  description: string;
  tags: string[];
  lyrics: string;
  coverArtUrl?: string;
}

interface MetadataFormProps {
  initialData: Partial<TrackMetadata>;
  onChange: (data: Partial<TrackMetadata>) => void;
  fileName?: string;
}

export const MetadataForm: React.FC<MetadataFormProps> = ({
  initialData,
  onChange,
  fileName,
}) => {
  const [data, setData] = useState<Partial<TrackMetadata>>(initialData);

  // Modal States
  const [showCoverModal, setShowCoverModal] = useState(false);
  const [showLyricsModal, setShowLyricsModal] = useState(false);
  const [showTagsModal, setShowTagsModal] = useState(false);

  useEffect(() => {
    setData(initialData);
  }, [initialData]);

  const updateField = (field: keyof TrackMetadata, value: any) => {
    const newData = { ...data, [field]: value };
    setData(newData);
    onChange(newData);
  };

  // Helper for quick validation state (simulated)
  const isValid = (field: string) => !!field && field.length > 0;

  return (
    <div className="animate-fadeIn">
      {/* Top Section: Cover & Basic Info */}
      <div className="flex flex-col md:flex-row gap-8 mb-8">
        {/* Cover Art Area */}
        <div className="w-full md:w-64 flex-shrink-0">
          <div
            className="aspect-square bg-kodo-ink border-2 border-dashed border-kodo-steel rounded-xl overflow-hidden relative group cursor-pointer hover:border-kodo-cyan/50 transition-all"
            onClick={() => setShowCoverModal(true)}
          >
            {data.coverArtUrl ? (
              <img
                src={data.coverArtUrl}
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="absolute inset-0 flex flex-col items-center justify-center text-gray-500 group-hover:text-kodo-cyan">
                <Music className="w-12 h-12 mb-2" />
                <span className="text-xs font-bold uppercase">
                  Upload Cover
                </span>
              </div>
            )}
            <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
              <Camera className="w-8 h-8 text-white" />
            </div>
          </div>
          <p className="text-center text-xs text-gray-500 mt-2">
            1000x1000px Min
          </p>
        </div>

        {/* Basic Info Fields */}
        <div className="flex-1 space-y-4">
          <Input
            label="Track Title"
            placeholder={fileName?.replace(/\.[^/.]+$/, '') || 'Enter title'}
            value={data.title || ''}
            onChange={(e) => updateField('title', e.target.value)}
            className={
              isValid(data.title || '')
                ? 'border-kodo-steel'
                : 'border-kodo-steel'
            } // visual cue logic could go here
          />

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label="Artist(s)"
              placeholder="Main Artist, Feat..."
              value={data.artist || ''}
              onChange={(e) => updateField('artist', e.target.value)}
            />
            <Input
              label="Album / EP"
              placeholder="Single or Album Name"
              value={data.album || ''}
              onChange={(e) => updateField('album', e.target.value)}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Input
              label="Genre"
              placeholder="e.g. Synthwave"
              value={data.genre || ''}
              onChange={(e) => updateField('genre', e.target.value)}
            />
            <Input
              label="BPM"
              placeholder="120"
              type="number"
              value={data.bpm || ''}
              onChange={(e) => updateField('bpm', e.target.value)}
            />
            <Input
              label="Key"
              placeholder="C Minor"
              value={data.key || ''}
              onChange={(e) => updateField('key', e.target.value)}
            />
          </div>
        </div>
      </div>

      <div className="w-full h-px bg-kodo-steel/50 mb-8"></div>

      {/* Advanced Details */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
        <div className="space-y-4">
          <h4 className="text-sm font-bold text-white uppercase tracking-wider mb-2">
            Publishing Details
          </h4>
          <Input
            label="Record Label"
            placeholder="Independent or Label Name"
            value={data.label || ''}
            onChange={(e) => updateField('label', e.target.value)}
          />
          <div className="grid grid-cols-2 gap-4">
            <Input
              label="Release Date"
              type="date"
              value={data.releaseDate || ''}
              onChange={(e) => updateField('releaseDate', e.target.value)}
            />
            <Input
              label="ISRC (Optional)"
              placeholder="CC-XXX-YY-NNNNN"
              value={data.isrc || ''}
              onChange={(e) => updateField('isrc', e.target.value)}
            />
          </div>
          <Input
            label="Copyright (C) / (P)"
            placeholder="© 2023 Artist Name"
            value={data.copyright || ''}
            onChange={(e) => updateField('copyright', e.target.value)}
          />
        </div>

        <div className="space-y-4">
          <h4 className="text-sm font-bold text-white uppercase tracking-wider mb-2">
            Metadata & Assets
          </h4>

          <div className="bg-kodo-ink rounded-lg p-4 border border-kodo-steel space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-300 flex items-center gap-2">
                <Hash className="w-4 h-4" /> Tags
              </span>
              <Button
                variant="ghost"
                size="sm"
                className="text-kodo-cyan"
                onClick={() => setShowTagsModal(true)}
              >
                {data.tags && data.tags.length > 0
                  ? `${data.tags.length} Selected`
                  : 'Add Tags'}
              </Button>
            </div>
            {data.tags && data.tags.length > 0 && (
              <div className="flex flex-wrap gap-1">
                {data.tags.map((t) => (
                  <span
                    key={t}
                    className="text-[10px] bg-kodo-slate px-2 py-1 rounded text-gray-300"
                  >
                    #{t}
                  </span>
                ))}
              </div>
            )}

            <div className="w-full h-px bg-kodo-steel/30"></div>

            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-300 flex items-center gap-2">
                <FileText className="w-4 h-4" /> Lyrics
              </span>
              <Button
                variant="ghost"
                size="sm"
                className={data.lyrics ? 'text-kodo-lime' : 'text-gray-400'}
                onClick={() => setShowLyricsModal(true)}
              >
                {data.lyrics ? (
                  <span className="flex items-center gap-1">
                    <Check className="w-3 h-3" /> Edited
                  </span>
                ) : (
                  'Add Lyrics'
                )}
              </Button>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-400 mb-2">
              Description
            </label>
            <textarea
              className="w-full bg-kodo-graphite border border-kodo-steel rounded-lg p-3 text-white focus:border-kodo-cyan outline-none min-h-[100px] text-sm"
              placeholder="Tell the story behind this track..."
              value={data.description || ''}
              onChange={(e) => updateField('description', e.target.value)}
            />
          </div>
        </div>
      </div>

      {/* Modals */}
      {showCoverModal && (
        <CoverArtUploadModal
          onClose={() => setShowCoverModal(false)}
          onSave={(url) => updateField('coverArtUrl', url)}
          currentImage={data.coverArtUrl}
        />
      )}
      {showLyricsModal && (
        <LyricsEditorModal
          onClose={() => setShowLyricsModal(false)}
          onSave={(text) => updateField('lyrics', text)}
          initialLyrics={data.lyrics}
        />
      )}
      {showTagsModal && (
        <TagSuggestionsModal
          onClose={() => setShowTagsModal(false)}
          selectedTags={data.tags || []}
          onUpdateTags={(tags) => updateField('tags', tags)}
        />
      )}
    </div>
  );
};
