import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { apiService, type Track } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Music } from 'lucide-react';

interface TrackEditDialogProps {
  track: Track;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onTrackUpdated?: (track: Track) => void;
}

export function TrackEditDialog({ track, open, onOpenChange, onTrackUpdated }: TrackEditDialogProps) {
  const [formData, setFormData] = useState({
    title: track.title,
    artist: track.artist,
    album: track.album || '',
    isPublic: track.isPublic || false,
  });
  const [isUpdating, setIsUpdating] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    setFormData({
      title: track.title,
      artist: track.artist,
      album: track.album || '',
      isPublic: track.isPublic || false,
    });
  }, [track]);

  const handleUpdate = async () => {
    if (!formData.title.trim() || !formData.artist.trim()) {
      toast({
        title: 'Missing fields',
        description: 'Title and artist are required',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsUpdating(true);
      const updated = await apiService.updateTrack(track.id, {
        title: formData.title,
        artist: formData.artist,
        album: formData.album || undefined,
        isPublic: formData.isPublic,
      });

      toast({
        title: 'Track updated',
        description: 'Metadata has been updated successfully.',
      });

      onTrackUpdated?.(updated);
      onOpenChange(false);
    } catch (error: any) {
      toast({
        title: 'Update failed',
        description: error.response?.data?.error || 'Failed to update track',
        variant: 'destructive',
      });
    } finally {
      setIsUpdating(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <Music className="h-5 w-5" />
            <span>Edit Track Metadata</span>
          </DialogTitle>
          <DialogDescription>
            Update the information for this track
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="title">Title *</Label>
            <Input
              id="title"
              placeholder="Song title"
              value={formData.title}
              onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="artist">Artist *</Label>
            <Input
              id="artist"
              placeholder="Artist name"
              value={formData.artist}
              onChange={(e) => setFormData(prev => ({ ...prev, artist: e.target.value }))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="album">Album</Label>
            <Input
              id="album"
              placeholder="Album name (optional)"
              value={formData.album}
              onChange={(e) => setFormData(prev => ({ ...prev, album: e.target.value }))}
            />
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="isPublic"
              checked={formData.isPublic}
              onChange={(e) => setFormData(prev => ({ ...prev, isPublic: e.target.checked }))}
              className="h-4 w-4"
            />
            <Label htmlFor="isPublic" className="cursor-pointer">
              Make this track public
            </Label>
          </div>

          <div className="p-3 bg-muted rounded-md text-sm text-muted-foreground">
            <div className="grid grid-cols-2 gap-2">
              <div>
                <span className="font-medium">Format:</span> {track.format?.toUpperCase() || 'UNKNOWN'}
              </div>
              <div>
                <span className="font-medium">Size:</span> {(track.size / 1024 / 1024).toFixed(2)} MB
              </div>
              {track.duration && (
                <div>
                  <span className="font-medium">Duration:</span> {Math.floor(track.duration / 60)}:{(track.duration % 60).toString().padStart(2, '0')}
                </div>
              )}
              {track.bitrate && (
                <div>
                  <span className="font-medium">Bitrate:</span> {track.bitrate}kbps
                </div>
              )}
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isUpdating}
          >
            Cancel
          </Button>
          <Button
            onClick={handleUpdate}
            disabled={isUpdating}
          >
            {isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            Save Changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

