'use client';

import * as React from 'react';
import { Circle, Headphones, MoreHorizontal, ChevronRight, ChevronDown, ChevronUp } from 'lucide-react';
import { CircularKnob } from '@/components/ui/CircularKnob';
import { TrackFader } from './TrackFader';
import { cn } from '@/lib/utils/cn';

export interface TrackControlsProps {
  trackName: string;
  trackColor: string;
  collapsed: boolean;
  volume: number;
  pan: number;
  peakLevel: number;
  rmsLevel: number;
  isMuted?: boolean;
  isSolo?: boolean;
  isRecordEnabled?: boolean;
  showAutomation?: boolean;
  showEffects?: boolean;
  isRecording?: boolean;
  mobileCollapsed?: boolean; // For mobile view collapsible controls
  onNameChange: (name: string) => void;
  onToggleCollapse: () => void;
  onVolumeChange: (volume: number) => void;
  onPanChange: (pan: number) => void;
  onMuteToggle: () => void;
  onSoloToggle?: () => void;
  onRecordToggle?: () => void;
  onAutomationToggle?: () => void;
  onEffectsClick?: () => void;
  onVolumeTouchStart?: () => void;
  onVolumeTouchEnd?: () => void;
  onPanTouchStart?: () => void;
  onPanTouchEnd?: () => void;
  onToggleMobileCollapse?: () => void;
  className?: string;
}

export function TrackControls({
  trackName,
  trackColor,
  collapsed,
  volume,
  pan,
  peakLevel,
  rmsLevel,
  isMuted = false,
  isSolo = false,
  isRecordEnabled = false,
  showAutomation = false,
  showEffects = false,
  isRecording = false,
  mobileCollapsed = false,
  onNameChange,
  onToggleCollapse,
  onVolumeChange,
  onPanChange,
  onMuteToggle,
  onSoloToggle,
  onRecordToggle,
  onAutomationToggle,
  onEffectsClick,
  onVolumeTouchStart,
  onVolumeTouchEnd,
  onPanTouchStart,
  onPanTouchEnd,
  onToggleMobileCollapse,
  className,
}: TrackControlsProps) {
  const [isEditingName, setIsEditingName] = React.useState(false);
  const [editName, setEditName] = React.useState(trackName);

  const handleNameClick = () => {
    setIsEditingName(true);
    setEditName(trackName);
  };

  const handleNameBlur = () => {
    setIsEditingName(false);
    if (editName.trim() && editName !== trackName) {
      onNameChange(editName.trim());
    } else {
      setEditName(trackName);
    }
  };

  const handleNameKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleNameBlur();
    } else if (e.key === 'Escape') {
      setIsEditingName(false);
      setEditName(trackName);
    }
  };

  // Mobile collapsed view - minimal controls (like master controls)
  if (mobileCollapsed) {
    return (
      <div className={cn(
        'flex flex-col items-center gap-2 px-3 py-2 bg-card/50 border border-accent/50 rounded-lg w-full sm:hidden',
        className
      )}>
        <div className="flex items-center justify-between w-full">
          <div className="flex items-center gap-1 flex-1">
            <button
              onClick={onToggleCollapse}
              className="p-0.5 hover:bg-accent/20 rounded transition-colors flex-shrink-0"
              title={collapsed ? 'Expand track' : 'Collapse track'}
            >
              {collapsed ? (
                <ChevronRight className="h-3 w-3 text-muted-foreground" />
              ) : (
                <ChevronDown className="h-3 w-3 text-muted-foreground" />
              )}
            </button>
            <div
              className="text-xs font-bold uppercase tracking-wider"
              style={{ color: trackColor }}
            >
              {trackName}
            </div>
          </div>
          {onToggleMobileCollapse && (
            <button
              onClick={onToggleMobileCollapse}
              className="p-1 hover:bg-accent/20 rounded transition-colors"
              title="Expand track controls"
            >
              <ChevronDown className="h-3 w-3 text-muted-foreground" />
            </button>
          )}
        </div>
        <div className="flex items-center gap-1 w-full justify-center">
          {onRecordToggle && (
            <button
              onClick={onRecordToggle}
              className={cn(
                'h-7 w-7 rounded-full flex items-center justify-center transition-all',
                isRecordEnabled
                  ? isRecording
                    ? 'bg-red-500 shadow-lg shadow-red-500/50 animate-pulse'
                    : 'bg-red-500 shadow-md shadow-red-500/30'
                  : 'bg-card hover:bg-accent border border-border/50'
              )}
              title={isRecordEnabled ? 'Record Armed' : 'Arm for Recording'}
            >
              <Circle className={cn('h-3.5 w-3.5', isRecordEnabled ? 'fill-white text-white' : 'text-muted-foreground')} />
            </button>
          )}
          <button
            onClick={onMuteToggle}
            className={cn(
              'h-7 w-7 rounded-md flex items-center justify-center transition-all text-xs font-bold',
              isMuted
                ? 'bg-blue-500 text-white shadow-md shadow-blue-500/30'
                : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
            )}
            title={isMuted ? 'Unmute' : 'Mute'}
          >
            M
          </button>
          {onSoloToggle && (
            <button
              onClick={onSoloToggle}
              className={cn(
                'h-7 w-7 rounded-md flex items-center justify-center transition-all text-xs font-bold',
                isSolo
                  ? 'bg-yellow-500 text-white shadow-md shadow-yellow-500/30'
                  : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
              )}
              title={isSolo ? 'Unsolo' : 'Solo'}
            >
              S
            </button>
          )}
          <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
            <div
              className={cn(
                'h-full transition-all',
                peakLevel > 0.95 ? 'bg-red-500' : peakLevel > 0.8 ? 'bg-yellow-500' : 'bg-green-500'
              )}
              style={{ width: `${peakLevel * 100}%` }}
            />
          </div>
        </div>
      </div>
    );
  }

  // Mobile expanded view - full controls (like master controls)
  const mobileExpandedView = (
    <div className={cn(
      'flex flex-col items-center gap-3 px-3 py-3 bg-card/50 border border-accent/50 rounded-lg w-full sm:hidden',
      className
    )}>
      {/* Header with collapse button */}
      <div className="flex items-center justify-between w-full">
        <button
          onClick={onToggleCollapse}
          className="p-0.5 hover:bg-accent/20 rounded transition-colors flex-shrink-0"
          title={collapsed ? 'Expand track' : 'Collapse track'}
        >
          {collapsed ? (
            <ChevronRight className="h-3 w-3 text-muted-foreground" />
          ) : (
            <ChevronDown className="h-3 w-3 text-muted-foreground" />
          )}
        </button>
        <div
          className="text-xs font-bold uppercase tracking-wider flex-1 text-center"
          style={{ color: trackColor }}
        >
          {trackName}
        </div>
        {onToggleMobileCollapse && (
          <button
            onClick={onToggleMobileCollapse}
            className="p-0.5 hover:bg-accent/20 rounded transition-colors flex-shrink-0"
            title="Collapse track controls"
          >
            <ChevronUp className="h-3 w-3 text-muted-foreground" />
          </button>
        )}
      </div>

      {/* Pan Control */}
      <CircularKnob
        value={pan}
        onChange={onPanChange}
        onTouchStart={onPanTouchStart}
        onTouchEnd={onPanTouchEnd}
        min={-1}
        max={1}
        step={0.01}
        label="PAN"
        size={48}
        formatValue={(value: number) => {
          if (Math.abs(value) < 0.01) return 'C';
          if (value < 0) return `${Math.abs(value * 100).toFixed(0)}L`;
          return `${(value * 100).toFixed(0)}R`;
        }}
      />

      {/* Volume Fader - Full height, not compressed */}
      <div className="flex-1 flex justify-center items-center w-full min-h-[160px]">
        <TrackFader
          value={volume}
          peakLevel={peakLevel}
          rmsLevel={rmsLevel}
          onChange={onVolumeChange}
          onTouchStart={onVolumeTouchStart}
          onTouchEnd={onVolumeTouchEnd}
        />
      </div>

      {/* Control buttons */}
      <div className="flex items-center gap-1 w-full justify-center">
        {onRecordToggle && (
          <button
            onClick={onRecordToggle}
            className={cn(
              'h-8 w-8 rounded-full flex items-center justify-center transition-all',
              isRecordEnabled
                ? isRecording
                  ? 'bg-red-500 shadow-lg shadow-red-500/50 animate-pulse'
                  : 'bg-red-500 shadow-md shadow-red-500/30'
                : 'bg-card hover:bg-accent border border-border/50'
            )}
            title={isRecordEnabled ? 'Record Armed' : 'Arm for Recording'}
          >
            <Circle className={cn('h-3.5 w-3.5', isRecordEnabled ? 'fill-white text-white' : 'text-muted-foreground')} />
          </button>
        )}
        <button
          onClick={onMuteToggle}
          className={cn(
            'h-8 w-8 rounded-md flex items-center justify-center transition-all text-xs font-bold',
            isMuted
              ? 'bg-blue-500 text-white shadow-md shadow-blue-500/30'
              : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
          )}
          title={isMuted ? 'Unmute' : 'Mute'}
        >
          M
        </button>
        {onSoloToggle && (
          <button
            onClick={onSoloToggle}
            className={cn(
              'h-8 w-8 rounded-md flex items-center justify-center transition-all text-xs font-bold',
              isSolo
                ? 'bg-yellow-500 text-white shadow-md shadow-yellow-500/30'
                : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
            )}
            title={isSolo ? 'Unsolo' : 'Solo'}
          >
            S
          </button>
        )}
        {onEffectsClick && (
          <button
            onClick={onEffectsClick}
            className={cn(
              'h-8 w-8 rounded-md flex items-center justify-center transition-all text-xs font-bold',
              showEffects
                ? 'bg-purple-500 text-white shadow-md shadow-purple-500/30'
                : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
            )}
            title="Effects"
          >
            FX
          </button>
        )}
      </div>
    </div>
  );

  return (
    <>
      {/* Mobile view - Show expanded or collapsed */}
      {!mobileCollapsed && mobileExpandedView}

      {/* Desktop/tablet view - hidden on mobile */}
      <div className={cn(
        'flex flex-col items-center gap-3 px-4 py-3 bg-card/50 border border-accent/50 rounded-lg hidden sm:flex',
        className
      )}>
      {/* Track Name Header with Collapse Chevron */}
      <div className="flex items-center gap-1 w-full">
        <button
          onClick={onToggleCollapse}
          className="p-0.5 hover:bg-accent/20 rounded transition-colors flex-shrink-0"
          title={collapsed ? 'Expand track' : 'Collapse track'}
        >
          {collapsed ? (
            <ChevronRight className="h-3 w-3 text-muted-foreground" />
          ) : (
            <ChevronDown className="h-3 w-3 text-muted-foreground" />
          )}
        </button>
        <div className="flex-1 flex items-center justify-center min-w-0">
          {isEditingName ? (
            <input
              type="text"
              value={editName}
              onChange={(e) => setEditName(e.target.value)}
              onBlur={handleNameBlur}
              onKeyDown={handleNameKeyDown}
              autoFocus
              className="w-24 text-[10px] font-bold uppercase tracking-wider text-center bg-transparent border-b focus:outline-none px-1"
              style={{ color: trackColor, borderColor: trackColor }}
            />
          ) : (
            <div
              onClick={handleNameClick}
              className="w-24 text-[10px] font-bold uppercase tracking-wider text-center cursor-text hover:bg-accent/10 px-1 rounded transition-colors truncate"
              style={{ color: trackColor }}
              title="Click to edit track name"
            >
              {trackName}
            </div>
          )}
        </div>
        {/* Spacer to balance the chevron and center the label */}
        <div className="p-0.5 flex-shrink-0 w-4" />
      </div>

      {/* Pan Control - Top */}
      <div className="flex justify-center w-full">
        <CircularKnob
          value={pan}
          onChange={onPanChange}
          onTouchStart={onPanTouchStart}
          onTouchEnd={onPanTouchEnd}
          min={-1}
          max={1}
          step={0.01}
          label="PAN"
          size={48}
          formatValue={(value: number) => {
            if (Math.abs(value) < 0.01) return 'C';
            if (value < 0) return `${Math.abs(value * 100).toFixed(0)}L`;
            return `${(value * 100).toFixed(0)}R`;
          }}
        />
      </div>

      {/* Track Fader - Center (vertically centered in remaining space) */}
      <div className="flex justify-center items-center flex-1 w-full">
        <TrackFader
          value={volume}
          peakLevel={peakLevel}
          rmsLevel={rmsLevel}
          onChange={onVolumeChange}
          onTouchStart={onVolumeTouchStart}
          onTouchEnd={onVolumeTouchEnd}
        />
      </div>

      {/* Control Buttons - Bottom */}
      <div className="flex flex-col gap-1 w-full">
        {/* Control Buttons Row 1: R/M/S */}
        <div className="flex items-center gap-1 w-full justify-center">
          {/* Record Arm */}
          {onRecordToggle && (
            <button
              onClick={onRecordToggle}
              className={cn(
                'h-8 w-8 rounded-md flex items-center justify-center transition-all text-[11px] font-bold',
                isRecordEnabled
                  ? 'bg-red-500 text-white shadow-md shadow-red-500/30'
                  : 'bg-card hover:bg-accent text-muted-foreground border border-border/50',
                isRecording && 'animate-pulse'
              )}
              title="Arm track for recording"
            >
              <Circle className="h-3 w-3 fill-current" />
            </button>
          )}

          {/* Mute Button */}
          <button
            onClick={onMuteToggle}
            className={cn(
              'h-8 w-8 rounded-md flex items-center justify-center transition-all text-[11px] font-bold',
              isMuted
                ? 'bg-blue-500 text-white shadow-md shadow-blue-500/30'
                : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
            )}
            title="Mute track"
          >
            M
          </button>

          {/* Solo Button */}
          {onSoloToggle && (
            <button
              onClick={onSoloToggle}
              className={cn(
                'h-8 w-8 rounded-md flex items-center justify-center transition-all text-[11px] font-bold',
                isSolo
                  ? 'bg-yellow-500 text-black shadow-md shadow-yellow-500/30'
                  : 'bg-card hover:bg-accent text-muted-foreground border border-border/50'
              )}
              title="Solo track"
            >
              <Headphones className="h-3 w-3" />
            </button>
          )}
        </div>
      </div>
      </div>
    </>
  );
}
