'use client';

import * as React from 'react';
import { Circle, Headphones, MoreHorizontal, ChevronRight, ChevronDown } 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;
  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;
  className?: string;
}

export function TrackControls({
  trackName,
  trackColor,
  collapsed,
  volume,
  pan,
  peakLevel,
  rmsLevel,
  isMuted = false,
  isSolo = false,
  isRecordEnabled = false,
  showAutomation = false,
  showEffects = false,
  isRecording = false,
  onNameChange,
  onToggleCollapse,
  onVolumeChange,
  onPanChange,
  onMuteToggle,
  onSoloToggle,
  onRecordToggle,
  onAutomationToggle,
  onEffectsClick,
  onVolumeTouchStart,
  onVolumeTouchEnd,
  onPanTouchStart,
  onPanTouchEnd,
  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);
    }
  };

  return (
    <div className={cn(
      'flex flex-col items-center gap-3 px-4 py-3 bg-card/50 border-2 border-accent/50 rounded-lg',
      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>
  );
}
