import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { GripVertical, X, UserX, TrendingUp, TrendingDown, Minus } from 'lucide-react';
import { Appointment } from '../../types';
import { subDays, subMonths, isAfter } from 'date-fns';

interface NoShowRateWidgetProps {
  appointments: Appointment[];
  isEditing?: boolean;
  onRemove?: () => void;
}

const NoShowRateWidget: React.FC<NoShowRateWidgetProps> = ({
  appointments,
  isEditing,
  onRemove,
}) => {
  const { t } = useTranslation();

  const noShowData = useMemo(() => {
    const now = new Date();
    const oneWeekAgo = subDays(now, 7);
    const twoWeeksAgo = subDays(now, 14);
    const oneMonthAgo = subMonths(now, 1);
    const twoMonthsAgo = subMonths(now, 2);

    // Calculate rates for different periods
    const calculateRate = (appts: Appointment[]) => {
      const completed = appts.filter(
        (a) => a.status === 'COMPLETED' || a.status === 'NO_SHOW' || a.status === 'CANCELLED'
      );
      const noShows = completed.filter((a) => a.status === 'NO_SHOW');
      return completed.length > 0 ? (noShows.length / completed.length) * 100 : 0;
    };

    // Current week
    const thisWeekAppts = appointments.filter((a) => isAfter(new Date(a.startTime), oneWeekAgo));
    const currentWeekRate = calculateRate(thisWeekAppts);

    // Last week
    const lastWeekAppts = appointments.filter(
      (a) => isAfter(new Date(a.startTime), twoWeeksAgo) && !isAfter(new Date(a.startTime), oneWeekAgo)
    );
    const lastWeekRate = calculateRate(lastWeekAppts);

    // Current month
    const thisMonthAppts = appointments.filter((a) => isAfter(new Date(a.startTime), oneMonthAgo));
    const currentMonthRate = calculateRate(thisMonthAppts);

    // Last month
    const lastMonthAppts = appointments.filter(
      (a) => isAfter(new Date(a.startTime), twoMonthsAgo) && !isAfter(new Date(a.startTime), oneMonthAgo)
    );
    const lastMonthRate = calculateRate(lastMonthAppts);

    // Calculate changes (negative is good for no-show rate)
    const weeklyChange = lastWeekRate !== 0 ? ((currentWeekRate - lastWeekRate) / lastWeekRate) * 100 : 0;
    const monthlyChange = lastMonthRate !== 0 ? ((currentMonthRate - lastMonthRate) / lastMonthRate) * 100 : 0;

    // Count total no-shows this month
    const noShowsThisMonth = thisMonthAppts.filter((a) => a.status === 'NO_SHOW').length;

    return {
      currentRate: currentMonthRate,
      noShowCount: noShowsThisMonth,
      weeklyChange,
      monthlyChange,
    };
  }, [appointments]);

  const formatChange = (change: number) => {
    if (change === 0) return '0%';
    return change > 0 ? `+${change.toFixed(1)}%` : `${change.toFixed(1)}%`;
  };

  // For no-show rate, down is good (green), up is bad (red)
  const getTrendIcon = (change: number) => {
    if (change < 0) return <TrendingDown size={12} className="mr-1" />;
    if (change > 0) return <TrendingUp size={12} className="mr-1" />;
    return <Minus size={12} className="mr-1" />;
  };

  const getTrendClass = (change: number) => {
    if (change < 0) return 'text-green-700 bg-green-50 dark:bg-green-900/30 dark:text-green-400';
    if (change > 0) return 'text-red-700 bg-red-50 dark:bg-red-900/30 dark:text-red-400';
    return 'text-gray-700 bg-gray-50 dark:bg-gray-700 dark:text-gray-300';
  };

  const getRateColor = (rate: number) => {
    if (rate <= 5) return 'text-green-600 dark:text-green-400';
    if (rate <= 10) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-red-600 dark:text-red-400';
  };

  return (
    <div className="h-full p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm relative group">
      {isEditing && (
        <>
          <div className="absolute top-2 left-2 cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 drag-handle">
            <GripVertical size={16} />
          </div>
          <button
            onClick={onRemove}
            className="absolute top-2 right-2 p-1 text-gray-400 hover:text-red-500 dark:hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
          >
            <X size={14} />
          </button>
        </>
      )}

      <div className={isEditing ? 'pl-5' : ''}>
        <div className="flex items-center gap-2 mb-2">
          <UserX size={18} className="text-gray-400" />
          <p className="text-sm font-medium text-gray-500 dark:text-gray-400">{t('dashboard.noShowRate')}</p>
        </div>

        <div className="flex items-baseline gap-2 mb-1">
          <span className={`text-2xl font-bold ${getRateColor(noShowData.currentRate)}`}>
            {noShowData.currentRate.toFixed(1)}%
          </span>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            ({noShowData.noShowCount} {t('dashboard.thisMonth')})
          </span>
        </div>

        <div className="flex flex-wrap gap-2 text-xs mt-2">
          <div className="flex items-center gap-1">
            <span className="text-gray-500 dark:text-gray-400">{t('dashboard.week')}:</span>
            <span className={`flex items-center px-1.5 py-0.5 rounded-full ${getTrendClass(noShowData.weeklyChange)}`}>
              {getTrendIcon(noShowData.weeklyChange)}
              {formatChange(noShowData.weeklyChange)}
            </span>
          </div>
          <div className="flex items-center gap-1">
            <span className="text-gray-500 dark:text-gray-400">{t('dashboard.month')}:</span>
            <span className={`flex items-center px-1.5 py-0.5 rounded-full ${getTrendClass(noShowData.monthlyChange)}`}>
              {getTrendIcon(noShowData.monthlyChange)}
              {formatChange(noShowData.monthlyChange)}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default NoShowRateWidget;
