import React from 'react';
import {
  Typography,
  Box,
  Skeleton,
  Chip,
} from '@mui/material';
import { AssignmentInd } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { format, isPast } from 'date-fns';
import { de } from 'date-fns/locale';
import { vikunjaApi } from '../../services/vikunja';
import type { VikunjaTask } from '../../types/vikunja.types';
import { safeOpenUrl } from '../../utils/safeOpenUrl';
import { useCountUp } from '../../hooks/useCountUp';
import { ListCard } from '../templates/ListCard';
import { WidgetCard } from '../templates/WidgetCard';

const PRIORITY_LABELS: Record<number, { label: string; color: 'default' | 'warning' | 'error' }> = {
  0: { label: 'Keine', color: 'default' },
  1: { label: 'Niedrig', color: 'default' },
  2: { label: 'Mittel', color: 'default' },
  3: { label: 'Hoch', color: 'warning' },
  4: { label: 'Kritisch', color: 'error' },
  5: { label: 'Dringend', color: 'error' },
};

const TaskRow: React.FC<{ task: VikunjaTask; vikunjaUrl: string }> = ({
  task,
  vikunjaUrl,
}) => {
  const handleClick = () => {
    safeOpenUrl(`${vikunjaUrl}/tasks/${task.id}`);
  };

  const dueDateStr = task.due_date
    ? format(new Date(task.due_date), 'dd. MMM', { locale: de })
    : null;
  const overdue = task.due_date ? isPast(new Date(task.due_date)) : false;
  const priority = PRIORITY_LABELS[task.priority] ?? PRIORITY_LABELS[0];

  return (
    <Box
      onClick={handleClick}
      sx={{
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        px: 1,
        cursor: 'pointer',
        borderRadius: 1,
        transition: 'background-color 0.15s ease',
        '&:hover': { bgcolor: 'action.hover' },
      }}
    >
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Typography variant="subtitle2" noWrap>
          {task.title}
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mt: 0.5, flexWrap: 'wrap' }}>
          {dueDateStr && (
            <Typography
              variant="caption"
              color={overdue ? 'error' : 'text.secondary'}
            >
              {dueDateStr}
            </Typography>
          )}
          {task.priority > 0 && (
            <Chip
              label={priority.label}
              size="small"
              color={priority.color}
              sx={{ height: 18, fontSize: '0.65rem' }}
            />
          )}
        </Box>
      </Box>
    </Box>
  );
};

const VikunjaMyTasksWidget: React.FC = () => {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['vikunja-my-tasks'],
    queryFn: () => vikunjaApi.getMyTasks(),
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const configured = data?.configured ?? true;
  const tasks = data?.data ?? [];
  const animatedTaskCount = useCountUp(tasks.length);

  if (!configured) {
    return (
      <WidgetCard
        title="Meine Aufgaben"
        icon={<AssignmentInd />}
        isEmpty
        emptyMessage="Vikunja nicht eingerichtet"
      />
    );
  }

  if (isError) {
    return (
      <WidgetCard
        title="Meine Aufgaben"
        icon={<AssignmentInd />}
        isError
        errorMessage="Vikunja nicht erreichbar"
      />
    );
  }

  const titleAction = !isLoading && !isError && tasks.length > 0 ? (
    <Chip label={animatedTaskCount} size="small" />
  ) : undefined;

  return (
    <ListCard
      title="Meine Aufgaben"
      icon={<AssignmentInd />}
      action={titleAction}
      items={tasks}
      renderItem={(task) => (
        <TaskRow key={task.id} task={task} vikunjaUrl={data?.vikunjaUrl ?? ''} />
      )}
      isLoading={isLoading}
      skeletonCount={3}
      skeletonItem={
        <Box sx={{ mb: 0.5 }}>
          <Skeleton variant="text" width="70%" height={22} animation="wave" />
          <Skeleton variant="text" width="40%" height={18} animation="wave" />
        </Box>
      }
      emptyMessage="Keine offenen Aufgaben"
    />
  );
};

export default VikunjaMyTasksWidget;
