import { useState, useEffect } from 'react';
import { Video, VideoOff, Clock, CheckCircle, XCircle, AlertTriangle, RefreshCw } from 'lucide-react';
import { matchingAPI } from '../../services/api';
import Avatar from '../common/Avatar';
import { SUGGESTION_STATUS, SUGGESTION_TYPE } from '../../constants';

/**
 * RecordingTab - Main component for managing recording partnerships
 * Shows suggestions for who will record user's heats and who user needs to record
 */
const RecordingTab = ({ slug, event, myHeats }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [suggestions, setSuggestions] = useState(null);
  const [recorderOptOut, setRecorderOptOut] = useState(false);
  const [updatingOptOut, setUpdatingOptOut] = useState(false);
  const [runningMatching, setRunningMatching] = useState(false);

  // Load suggestions on mount
  useEffect(() => {
    loadSuggestions();
  }, [slug]);

  const loadSuggestions = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await matchingAPI.getSuggestions(slug);
      setSuggestions(data);
    } catch (err) {
      console.error('Failed to load suggestions:', err);
      setError('Failed to load suggestions');
    } finally {
      setLoading(false);
    }
  };

  const handleOptOutChange = async (newValue) => {
    try {
      setUpdatingOptOut(true);
      await matchingAPI.setRecorderOptOut(slug, newValue);
      setRecorderOptOut(newValue);
    } catch (err) {
      console.error('Failed to update opt-out:', err);
    } finally {
      setUpdatingOptOut(false);
    }
  };

  const handleUpdateStatus = async (suggestionId, status) => {
    try {
      await matchingAPI.updateSuggestionStatus(slug, suggestionId, status);
      // Reload suggestions
      await loadSuggestions();
    } catch (err) {
      console.error('Failed to update suggestion status:', err);
    }
  };

  const handleRunMatching = async () => {
    try {
      setRunningMatching(true);
      await matchingAPI.runMatching(slug);
      await loadSuggestions();
    } catch (err) {
      console.error('Failed to run matching:', err);
    } finally {
      setRunningMatching(false);
    }
  };

  // Calculate countdown to matching
  const getCountdown = () => {
    if (!event?.registrationDeadline) return null;
    const deadline = new Date(event.registrationDeadline);
    const now = new Date();
    const diff = deadline.getTime() - now.getTime();

    if (diff <= 0) return null;

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    return { hours, minutes };
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="flex flex-col items-center gap-3">
          <RefreshCw className="w-8 h-8 animate-spin text-primary-600" />
          <p className="text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4">
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
          {error}
        </div>
      </div>
    );
  }

  const countdown = getCountdown();
  const toBeRecorded = suggestions?.toBeRecorded || [];
  const toRecord = suggestions?.toRecord || [];
  const matchingRunAt = suggestions?.matchingRunAt;

  return (
    <div className="p-4 space-y-6 overflow-y-auto h-full">
      {/* Header with info */}
      <div className="bg-gradient-to-r from-primary-50 to-primary-100 rounded-lg p-4">
        <div className="flex items-center gap-3 mb-2">
          <Video className="w-6 h-6 text-primary-600" />
          <h3 className="text-lg font-semibold text-primary-900">Recording</h3>
        </div>
        <p className="text-sm text-primary-700">
          System automatically pairs people for mutual recording of performances.
        </p>
      </div>

      {/* Countdown or Status */}
      {countdown ? (
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
          <div className="flex items-center gap-3">
            <Clock className="w-5 h-5 text-amber-600" />
            <div>
              <p className="font-medium text-amber-800">
                Matching will run in: {countdown.hours}h {countdown.minutes}min
              </p>
              <p className="text-sm text-amber-600">
                After registration closes, the system will automatically pair recording partners.
              </p>
            </div>
          </div>
        </div>
      ) : matchingRunAt ? (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <CheckCircle className="w-5 h-5 text-green-600" />
              <div>
                <p className="font-medium text-green-800">Matching completed</p>
                <p className="text-sm text-green-600">
                  Last run: {new Date(matchingRunAt).toLocaleString('en-US')}
                </p>
              </div>
            </div>
            <button
              onClick={handleRunMatching}
              disabled={runningMatching}
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${runningMatching ? 'animate-spin' : ''}`} />
              {runningMatching ? 'Running...' : 'Run again'}
            </button>
          </div>
        </div>
      ) : (
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <AlertTriangle className="w-5 h-5 text-gray-500" />
              <p className="text-gray-600">Matching has not been run yet</p>
            </div>
            <button
              onClick={handleRunMatching}
              disabled={runningMatching}
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-primary-600 text-white rounded-md hover:bg-primary-700 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${runningMatching ? 'animate-spin' : ''}`} />
              {runningMatching ? 'Running...' : 'Run matching'}
            </button>
          </div>
        </div>
      )}

      {/* My heats to be recorded */}
      <div>
        <h4 className="flex items-center gap-2 text-md font-semibold text-gray-900 mb-3">
          <Video className="w-5 h-5 text-primary-600" />
          My heats to be recorded ({toBeRecorded.length})
        </h4>

        {toBeRecorded.length === 0 ? (
          <div className="bg-gray-50 rounded-lg p-4 text-center text-gray-500">
            {myHeats.length === 0
              ? "You haven't declared any heats"
              : 'No suggestions - run matching'
            }
          </div>
        ) : (
          <div className="space-y-2">
            {toBeRecorded.map((suggestion) => (
              <SuggestionCard
                key={suggestion.id || suggestion.heat?.id}
                suggestion={suggestion}
                type={SUGGESTION_TYPE.TO_BE_RECORDED}
                onAccept={() => handleUpdateStatus(suggestion.id, SUGGESTION_STATUS.ACCEPTED)}
                onReject={() => handleUpdateStatus(suggestion.id, SUGGESTION_STATUS.REJECTED)}
              />
            ))}
          </div>
        )}
      </div>

      {/* Heats I need to record */}
      <div>
        <h4 className="flex items-center gap-2 text-md font-semibold text-gray-900 mb-3">
          <VideoOff className="w-5 h-5 text-amber-600" />
          Recording others ({toRecord.length})
        </h4>

        {toRecord.length === 0 ? (
          <div className="bg-gray-50 rounded-lg p-4 text-center text-gray-500">
            You have no assigned heats to record
          </div>
        ) : (
          <div className="space-y-2">
            {toRecord.map((suggestion) => (
              <SuggestionCard
                key={suggestion.id || suggestion.heat?.id}
                suggestion={suggestion}
                type={SUGGESTION_TYPE.TO_RECORD}
                onAccept={() => handleUpdateStatus(suggestion.id, SUGGESTION_STATUS.ACCEPTED)}
                onReject={() => handleUpdateStatus(suggestion.id, SUGGESTION_STATUS.REJECTED)}
              />
            ))}
          </div>
        )}
      </div>

      {/* Opt-out toggle */}
      <div className="border-t pt-4">
        <label className="flex items-center gap-3 cursor-pointer">
          <input
            type="checkbox"
            checked={recorderOptOut}
            onChange={(e) => handleOptOutChange(e.target.checked)}
            disabled={updatingOptOut}
            className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
          />
          <span className="text-sm text-gray-700">
            I don't want to record others (opt-out)
          </span>
          {updatingOptOut && (
            <RefreshCw className="w-4 h-4 animate-spin text-gray-400" />
          )}
        </label>
        <p className="text-xs text-gray-500 mt-1 ml-7">
          If checked, you'll be deprioritized when assigning recording partners.
        </p>
      </div>
    </div>
  );
};

/**
 * SuggestionCard - Single suggestion item
 */
const SuggestionCard = ({ suggestion, type, onAccept, onReject }) => {
  const heat = suggestion.heat;
  const recorder = suggestion.recorder;
  const dancer = heat?.user;
  const status = suggestion.status;

  // Format heat info
  const heatInfo = heat
    ? `${heat.division?.abbreviation || '?'} ${heat.competitionType?.abbreviation || '?'} H${heat.heatNumber}`
    : 'Unknown heat';

  const person = type === SUGGESTION_TYPE.TO_BE_RECORDED ? recorder : dancer;
  const personLabel = type === SUGGESTION_TYPE.TO_BE_RECORDED ? 'Recording you:' : 'You record:';

  // Status badge
  const getStatusBadge = () => {
    switch (status) {
      case SUGGESTION_STATUS.ACCEPTED:
        return (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-green-100 text-green-800 rounded">
            <CheckCircle className="w-3 h-3" />
            Accepted
          </span>
        );
      case SUGGESTION_STATUS.REJECTED:
        return (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-red-100 text-red-800 rounded">
            <XCircle className="w-3 h-3" />
            Rejected
          </span>
        );
      case SUGGESTION_STATUS.NOT_FOUND:
        return (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-amber-100 text-amber-800 rounded">
            <AlertTriangle className="w-3 h-3" />
            Not found
          </span>
        );
      default:
        return null;
    }
  };

  // No recorder found
  if (status === SUGGESTION_STATUS.NOT_FOUND) {
    return (
      <div className="flex items-center justify-between p-3 bg-amber-50 border border-amber-200 rounded-lg">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center">
            <AlertTriangle className="w-5 h-5 text-amber-600" />
          </div>
          <div>
            <p className="font-medium text-amber-900">{heatInfo}</p>
            <p className="text-sm text-amber-700">No available partner found</p>
          </div>
        </div>
        {getStatusBadge()}
      </div>
    );
  }

  return (
    <div className="flex items-center justify-between p-3 bg-white border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
      <div className="flex items-center gap-3">
        {person ? (
          <Avatar
            src={person.avatar}
            username={person.username}
            size={40}
          />
        ) : (
          <div className="w-10 h-10 bg-gray-200 rounded-full" />
        )}
        <div>
          <p className="font-medium text-gray-900">{heatInfo}</p>
          <p className="text-sm text-gray-600">
            {personLabel} <span className="font-medium">@{person?.username || '?'}</span>
            {person?.city && (
              <span className="text-gray-400"> ({person.city})</span>
            )}
          </p>
        </div>
      </div>

      <div className="flex items-center gap-2">
        {status === SUGGESTION_STATUS.PENDING ? (
          <>
            <button
              onClick={onAccept}
              className="p-2 text-green-600 hover:bg-green-50 rounded-md transition-colors"
              title="Accept"
            >
              <CheckCircle className="w-5 h-5" />
            </button>
            <button
              onClick={onReject}
              className="p-2 text-red-600 hover:bg-red-50 rounded-md transition-colors"
              title="Reject"
            >
              <XCircle className="w-5 h-5" />
            </button>
          </>
        ) : (
          getStatusBadge()
        )}
      </div>
    </div>
  );
};

export default RecordingTab;
