'use client';

import { Play, Pause, StopCircle, Clock, Timer, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { useMeetingTimer, useMeetingCountdown } from '@/hooks/lean/use-meeting-timer';
import type { MeetingStatus } from '@/types/lean';

interface MeetingTimerProps {
  /** Current meeting status */
  status: MeetingStatus;
  /** Meeting start time (for calculating elapsed time) */
  startTime?: string | null;
  /** Meeting end time */
  endTime?: string | null;
  /** Total duration in minutes (for display after meeting ends) */
  duration?: number | null;
  /** Target duration in minutes for countdown mode */
  targetMinutes?: number;
  /** Callback when start is clicked */
  onStart?: () => void;
  /** Callback when stop is clicked */
  onStop?: () => void;
  /** Loading state */
  isLoading?: boolean;
  /** Compact mode for smaller displays */
  compact?: boolean;
}

/**
 * Meeting Timer component for tracking meeting duration
 */
export function MeetingTimer({
  status,
  startTime,
  endTime,
  duration,
  targetMinutes = 15,
  onStart,
  onStop,
  isLoading = false,
  compact = false,
}: MeetingTimerProps) {
  // Use countdown timer if target is set, otherwise regular timer
  const countdown = useMeetingCountdown(targetMinutes);
  const regularTimer = useMeetingTimer(
    status === 'IN_PROGRESS' ? startTime : null,
    status === 'IN_PROGRESS'
  );

  // Determine which timer to use based on meeting status
  const isInProgress = status === 'IN_PROGRESS';
  const isCompleted = status === 'COMPLETED';
  const isScheduled = status === 'SCHEDULED';

  // Get the timer state based on mode
  const timer = targetMinutes ? countdown : regularTimer;
  const isOvertime = targetMinutes ? countdown.isOvertime : false;

  // Calculate displayed time
  let displayTime = timer.formattedTime;
  let displayLabel = 'Dauer';

  if (isCompleted && duration !== null && duration !== undefined) {
    const mins = Math.floor(duration);
    const secs = Math.round((duration - mins) * 60);
    displayTime = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    displayLabel = 'Gesamtdauer';
  } else if (isScheduled) {
    displayTime = targetMinutes ? `${targetMinutes}:00` : '00:00';
    displayLabel = targetMinutes ? 'Zielzeit' : 'Bereit';
  } else if (isInProgress && targetMinutes) {
    displayLabel = isOvertime ? 'Ueberzogen' : 'Verbleibend';
  }

  const handleStartStop = () => {
    if (isScheduled && onStart) {
      timer.start();
      onStart();
    } else if (isInProgress && onStop) {
      timer.pause();
      onStop();
    }
  };

  if (compact) {
    return (
      <TooltipProvider>
        <div className="flex items-center gap-2">
          <Tooltip>
            <TooltipTrigger asChild>
              <div
                className={cn(
                  'flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-mono font-medium',
                  isOvertime
                    ? 'bg-red-100 text-red-700'
                    : isInProgress
                      ? 'bg-blue-100 text-blue-700'
                      : isCompleted
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-700'
                )}
              >
                {isOvertime ? (
                  <AlertTriangle className="h-3.5 w-3.5" />
                ) : (
                  <Timer className="h-3.5 w-3.5" />
                )}
                {displayTime}
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p>{displayLabel}</p>
            </TooltipContent>
          </Tooltip>

          {!isCompleted && (
            <Button
              size="sm"
              variant={isInProgress ? 'destructive' : 'default'}
              onClick={handleStartStop}
              disabled={isLoading}
              className="h-8"
            >
              {isInProgress ? (
                <>
                  <StopCircle className="h-3.5 w-3.5 mr-1" />
                  Stop
                </>
              ) : (
                <>
                  <Play className="h-3.5 w-3.5 mr-1" />
                  Start
                </>
              )}
            </Button>
          )}
        </div>
      </TooltipProvider>
    );
  }

  return (
    <Card
      className={cn(
        'transition-colors',
        isOvertime
          ? 'border-red-300 bg-red-50'
          : isInProgress
            ? 'border-blue-300 bg-blue-50'
            : ''
      )}
    >
      <CardContent className="p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div
              className={cn(
                'p-2 rounded-full',
                isOvertime
                  ? 'bg-red-100'
                  : isInProgress
                    ? 'bg-blue-100'
                    : isCompleted
                      ? 'bg-green-100'
                      : 'bg-gray-100'
              )}
            >
              {isOvertime ? (
                <AlertTriangle
                  className={cn(
                    'h-5 w-5',
                    isOvertime ? 'text-red-600' : 'text-blue-600'
                  )}
                />
              ) : (
                <Clock
                  className={cn(
                    'h-5 w-5',
                    isInProgress
                      ? 'text-blue-600'
                      : isCompleted
                        ? 'text-green-600'
                        : 'text-gray-600'
                  )}
                />
              )}
            </div>

            <div>
              <div className="text-xs text-muted-foreground uppercase tracking-wide">
                {displayLabel}
              </div>
              <div
                className={cn(
                  'text-2xl font-mono font-bold tabular-nums',
                  isOvertime
                    ? 'text-red-700'
                    : isInProgress
                      ? 'text-blue-700'
                      : isCompleted
                        ? 'text-green-700'
                        : 'text-foreground'
                )}
              >
                {displayTime}
              </div>
            </div>
          </div>

          {!isCompleted && (
            <div className="flex gap-2">
              {isInProgress ? (
                <Button
                  variant="destructive"
                  onClick={handleStartStop}
                  disabled={isLoading}
                >
                  <StopCircle className="h-4 w-4 mr-2" />
                  Meeting beenden
                </Button>
              ) : (
                <Button onClick={handleStartStop} disabled={isLoading}>
                  <Play className="h-4 w-4 mr-2" />
                  Meeting starten
                </Button>
              )}
            </div>
          )}

          {isCompleted && (
            <div className="text-sm text-muted-foreground">
              Meeting abgeschlossen
            </div>
          )}
        </div>

        {targetMinutes && isInProgress && !isOvertime && (
          <div className="mt-3">
            <div className="w-full bg-gray-200 rounded-full h-1.5">
              <div
                className={cn(
                  'h-1.5 rounded-full transition-all',
                  countdown.remainingSeconds < 60
                    ? 'bg-red-500'
                    : countdown.remainingSeconds < 180
                      ? 'bg-yellow-500'
                      : 'bg-blue-500'
                )}
                style={{
                  width: `${Math.min(100, (timer.elapsedSeconds / (targetMinutes * 60)) * 100)}%`,
                }}
              />
            </div>
            <div className="flex justify-between text-xs text-muted-foreground mt-1">
              <span>0:00</span>
              <span>{targetMinutes}:00</span>
            </div>
          </div>
        )}

        {isOvertime && (
          <div className="mt-3 flex items-center gap-2 text-sm text-red-600">
            <AlertTriangle className="h-4 w-4" />
            <span>Zielzeit ueberschritten</span>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
