import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
  format,
  startOfDay,
  endOfDay,
  startOfWeek,
  endOfWeek,
  addDays,
  isToday,
  isTomorrow,
  isWithinInterval,
  parseISO,
  differenceInMinutes,
  isBefore,
  isAfter,
} from 'date-fns';
import {
  Calendar,
  Clock,
  User,
  CheckCircle,
  XCircle,
  TrendingUp,
  CalendarDays,
  CalendarOff,
  ArrowRight,
  PlayCircle,
} from 'lucide-react';
import apiClient from '../api/client';
import { User as UserType } from '../types';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';

interface StaffDashboardProps {
  user: UserType;
  linkedResourceName?: string;
}

interface Appointment {
  id: number;
  title: string;
  start_time: string;
  end_time: string;
  status: string;
  notes?: string;
  customer_name?: string;
  service_name?: string;
}

const StaffDashboard: React.FC<StaffDashboardProps> = ({ user }) => {
  const { t } = useTranslation();
  const userResourceId = user.linked_resource_id ?? null;
  const userResourceName = user.linked_resource_name ?? null;

  // Fetch this week's appointments for statistics
  const weekStart = startOfWeek(new Date(), { weekStartsOn: 1 });
  const weekEnd = endOfWeek(new Date(), { weekStartsOn: 1 });

  const { data: weekAppointments = [], isLoading } = useQuery({
    queryKey: ['staff-week-appointments', userResourceId, format(weekStart, 'yyyy-MM-dd')],
    queryFn: async () => {
      if (!userResourceId) return [];

      const response = await apiClient.get('/appointments/', {
        params: {
          resource: userResourceId,
          start_date: weekStart.toISOString(),
          end_date: weekEnd.toISOString(),
        },
      });

      return response.data.map((apt: any) => ({
        id: apt.id,
        title: apt.title || apt.service_name || 'Appointment',
        start_time: apt.start_time,
        end_time: apt.end_time,
        status: apt.status,
        notes: apt.notes,
        customer_name: apt.customer_name,
        service_name: apt.service_name,
      }));
    },
    enabled: !!userResourceId,
  });

  // Calculate statistics
  const stats = useMemo(() => {
    const now = new Date();
    const todayStart = startOfDay(now);
    const todayEnd = endOfDay(now);

    const todayAppointments = weekAppointments.filter((apt) =>
      isWithinInterval(parseISO(apt.start_time), { start: todayStart, end: todayEnd })
    );

    const completed = weekAppointments.filter(
      (apt) => apt.status === 'COMPLETED' || apt.status === 'PAID'
    ).length;

    const cancelled = weekAppointments.filter(
      (apt) => apt.status === 'CANCELLED' || apt.status === 'CANCELED'
    ).length;

    const noShows = weekAppointments.filter(
      (apt) => apt.status === 'NOSHOW' || apt.status === 'NO_SHOW'
    ).length;

    const scheduled = weekAppointments.filter(
      (apt) =>
        apt.status === 'SCHEDULED' ||
        apt.status === 'CONFIRMED' ||
        apt.status === 'PENDING'
    ).length;

    const inProgress = weekAppointments.filter(
      (apt) => apt.status === 'IN_PROGRESS'
    ).length;

    // Calculate total hours worked this week
    const totalMinutes = weekAppointments
      .filter((apt) => apt.status === 'COMPLETED' || apt.status === 'PAID')
      .reduce((acc, apt) => {
        const start = parseISO(apt.start_time);
        const end = parseISO(apt.end_time);
        return acc + differenceInMinutes(end, start);
      }, 0);

    const hoursWorked = Math.round(totalMinutes / 60 * 10) / 10;

    return {
      todayCount: todayAppointments.length,
      weekTotal: weekAppointments.length,
      completed,
      cancelled,
      noShows,
      scheduled,
      inProgress,
      hoursWorked,
      completionRate: weekAppointments.length > 0
        ? Math.round((completed / weekAppointments.length) * 100)
        : 0,
    };
  }, [weekAppointments]);

  // Get current or next appointment
  const currentOrNextAppointment = useMemo(() => {
    const now = new Date();

    // First check for in-progress
    const inProgress = weekAppointments.find((apt) => apt.status === 'IN_PROGRESS');
    if (inProgress) {
      return { type: 'current', appointment: inProgress };
    }

    // Find next upcoming appointment
    const upcoming = weekAppointments
      .filter(
        (apt) =>
          (apt.status === 'SCHEDULED' || apt.status === 'CONFIRMED' || apt.status === 'PENDING') &&
          isAfter(parseISO(apt.start_time), now)
      )
      .sort((a, b) => parseISO(a.start_time).getTime() - parseISO(b.start_time).getTime());

    if (upcoming.length > 0) {
      return { type: 'next', appointment: upcoming[0] };
    }

    return null;
  }, [weekAppointments]);

  // Get upcoming appointments (next 3 days)
  const upcomingAppointments = useMemo(() => {
    const now = new Date();
    const threeDaysLater = addDays(now, 3);

    return weekAppointments
      .filter(
        (apt) =>
          (apt.status === 'SCHEDULED' || apt.status === 'CONFIRMED' || apt.status === 'PENDING') &&
          isAfter(parseISO(apt.start_time), now) &&
          isBefore(parseISO(apt.start_time), threeDaysLater)
      )
      .sort((a, b) => parseISO(a.start_time).getTime() - parseISO(b.start_time).getTime())
      .slice(0, 5);
  }, [weekAppointments]);

  // Weekly chart data
  const weeklyChartData = useMemo(() => {
    const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    const dayMap: Record<string, number> = {};

    days.forEach((day) => {
      dayMap[day] = 0;
    });

    weekAppointments.forEach((apt) => {
      const date = parseISO(apt.start_time);
      const dayIndex = (date.getDay() + 6) % 7; // Convert to Mon=0, Sun=6
      const dayName = days[dayIndex];
      dayMap[dayName]++;
    });

    return days.map((day) => ({ name: day, appointments: dayMap[day] }));
  }, [weekAppointments]);

  const getStatusColor = (status: string) => {
    switch (status.toUpperCase()) {
      case 'SCHEDULED':
      case 'CONFIRMED':
      case 'PENDING':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
      case 'IN_PROGRESS':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
      case 'COMPLETED':
      case 'PAID':
        return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
      case 'CANCELLED':
      case 'CANCELED':
      case 'NOSHOW':
      case 'NO_SHOW':
        return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  const formatAppointmentDate = (dateStr: string) => {
    const date = parseISO(dateStr);
    if (isToday(date)) return t('staffDashboard.today', 'Today');
    if (isTomorrow(date)) return t('staffDashboard.tomorrow', 'Tomorrow');
    return format(date, 'EEE, MMM d');
  };

  // Show message if no resource is linked
  if (!userResourceId) {
    return (
      <div className="flex flex-col h-full bg-gray-50 dark:bg-gray-900 p-8">
        <div className="max-w-2xl mx-auto text-center">
          <Calendar size={64} className="mx-auto text-gray-300 dark:text-gray-600 mb-6" />
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-3">
            {t('staffDashboard.welcomeTitle', 'Welcome, {{name}}!', { name: user.name })}
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            {t(
              'staffDashboard.noResourceLinked',
              'Your account is not linked to a resource yet. Please contact your manager to set up your schedule.'
            )}
          </p>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="p-8 space-y-6">
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-64 mb-2"></div>
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div
              key={i}
              className="p-6 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 animate-pulse"
            >
              <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-2"></div>
              <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-16"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="p-8 space-y-6 bg-gray-50 dark:bg-gray-900 min-h-full">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
          {t('staffDashboard.welcomeTitle', 'Welcome, {{name}}!', { name: user.name })}
        </h1>
        <p className="text-gray-500 dark:text-gray-400">
          {t('staffDashboard.weekOverview', "Here's your week at a glance")}
        </p>
        {/* Resource Badge - Makes it clear which resource these stats are for */}
        {userResourceName && (
          <div className="mt-2 inline-flex items-center gap-2 px-3 py-1.5 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300 rounded-lg text-sm">
            <User size={14} />
            <span>
              {t('staffDashboard.viewingAs', 'Viewing appointments for:')}
            </span>
            <span className="font-semibold">{userResourceName}</span>
          </div>
        )}
      </div>

      {/* Current/Next Appointment Banner */}
      {currentOrNextAppointment && (
        <div
          className={`p-4 rounded-xl border-l-4 ${
            currentOrNextAppointment.type === 'current'
              ? 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-500'
              : 'bg-blue-50 dark:bg-blue-900/20 border-blue-500'
          }`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div
                className={`p-3 rounded-lg ${
                  currentOrNextAppointment.type === 'current'
                    ? 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-600'
                    : 'bg-blue-100 dark:bg-blue-900/40 text-blue-600'
                }`}
              >
                {currentOrNextAppointment.type === 'current' ? (
                  <PlayCircle size={24} />
                ) : (
                  <Clock size={24} />
                )}
              </div>
              <div>
                <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
                  {currentOrNextAppointment.type === 'current'
                    ? t('staffDashboard.currentAppointment', 'Current Appointment')
                    : t('staffDashboard.nextAppointment', 'Next Appointment')}
                </p>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {currentOrNextAppointment.appointment.service_name ||
                    currentOrNextAppointment.appointment.title}
                </h3>
                <div className="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-300 mt-1">
                  {currentOrNextAppointment.appointment.customer_name && (
                    <span className="flex items-center gap-1">
                      <User size={14} />
                      {currentOrNextAppointment.appointment.customer_name}
                    </span>
                  )}
                  <span className="flex items-center gap-1">
                    <Clock size={14} />
                    {format(parseISO(currentOrNextAppointment.appointment.start_time), 'h:mm a')} -{' '}
                    {format(parseISO(currentOrNextAppointment.appointment.end_time), 'h:mm a')}
                  </span>
                </div>
              </div>
            </div>
            <Link
              to="/my-schedule"
              className="px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors flex items-center gap-2"
            >
              {t('staffDashboard.viewSchedule', 'View Schedule')}
              <ArrowRight size={16} />
            </Link>
          </div>
        </div>
      )}

      {/* Stats Grid - Your Personal Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Your Appointments Today */}
        <div className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
              <Calendar size={18} className="text-blue-600" />
            </div>
            <span className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {t('staffDashboard.yourToday', 'Your Today')}
            </span>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {stats.todayCount}
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t('staffDashboard.yourAppointments', 'your appointments')}
          </p>
        </div>

        {/* Your Week Total */}
        <div className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-purple-100 dark:bg-purple-900/40 rounded-lg">
              <CalendarDays size={18} className="text-purple-600" />
            </div>
            <span className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {t('staffDashboard.yourWeek', 'Your Week')}
            </span>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {stats.weekTotal}
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t('staffDashboard.yourTotalAppointments', 'your total appointments')}
          </p>
        </div>

        {/* Your Completed */}
        <div className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-green-100 dark:bg-green-900/40 rounded-lg">
              <CheckCircle size={18} className="text-green-600" />
            </div>
            <span className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {t('staffDashboard.yourCompleted', 'You Completed')}
            </span>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {stats.completed}
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {stats.completionRate}% {t('staffDashboard.yourCompletionRate', 'your completion rate')}
          </p>
        </div>

        {/* Your Hours Worked */}
        <div className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-orange-100 dark:bg-orange-900/40 rounded-lg">
              <Clock size={18} className="text-orange-600" />
            </div>
            <span className="text-sm font-medium text-gray-500 dark:text-gray-400">
              {t('staffDashboard.yourHoursWorked', 'Your Hours')}
            </span>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {stats.hoursWorked}
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t('staffDashboard.yourThisWeek', 'worked this week')}
          </p>
        </div>
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Your Upcoming Appointments */}
        <div className="lg:col-span-1 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              {t('staffDashboard.yourUpcoming', 'Your Upcoming Appointments')}
            </h2>
            <Link
              to="/my-schedule"
              className="text-sm text-brand-600 hover:text-brand-700 dark:text-brand-400"
            >
              {t('common.viewAll', 'View All')}
            </Link>
          </div>

          {upcomingAppointments.length === 0 ? (
            <div className="text-center py-8">
              <Calendar size={40} className="mx-auto text-gray-300 dark:text-gray-600 mb-3" />
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('staffDashboard.noUpcomingForYou', 'You have no upcoming appointments')}
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {upcomingAppointments.map((apt) => (
                <div
                  key={apt.id}
                  className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-100 dark:border-gray-600"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <h4 className="text-sm font-medium text-gray-900 dark:text-white truncate">
                        {apt.service_name || apt.title}
                      </h4>
                      {apt.customer_name && (
                        <p className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1 mt-0.5">
                          <User size={10} />
                          {apt.customer_name}
                        </p>
                      )}
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        {formatAppointmentDate(apt.start_time)} at{' '}
                        {format(parseISO(apt.start_time), 'h:mm a')}
                      </p>
                    </div>
                    <span
                      className={`text-xs px-2 py-0.5 rounded-full font-medium ${getStatusColor(
                        apt.status
                      )}`}
                    >
                      {apt.status.replace('_', ' ')}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Your Weekly Chart */}
        <div className="lg:col-span-2 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {t('staffDashboard.yourWeeklyOverview', 'Your Weekly Schedule')}
          </h2>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%" minWidth={200} minHeight={150}>
              <BarChart data={weeklyChartData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#374151" strokeOpacity={0.2} />
                <XAxis
                  dataKey="name"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: '#9CA3AF', fontSize: 12 }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: '#9CA3AF', fontSize: 12 }}
                  allowDecimals={false}
                />
                <Tooltip
                  cursor={{ fill: 'rgba(107, 114, 128, 0.1)' }}
                  contentStyle={{
                    borderRadius: '8px',
                    border: 'none',
                    boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
                    backgroundColor: '#1F2937',
                    color: '#F3F4F6',
                  }}
                  formatter={(value: number) => [value, t('staffDashboard.appointments', 'Appointments')]}
                />
                <Bar dataKey="appointments" fill="#3b82f6" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Status Breakdown */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 flex items-center gap-3">
          <div className="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
            <Calendar size={18} className="text-blue-600" />
          </div>
          <div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">{stats.scheduled}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              {t('staffDashboard.scheduled', 'Scheduled')}
            </div>
          </div>
        </div>

        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 flex items-center gap-3">
          <div className="p-2 bg-yellow-100 dark:bg-yellow-900/40 rounded-lg">
            <TrendingUp size={18} className="text-yellow-600" />
          </div>
          <div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">{stats.inProgress}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              {t('staffDashboard.inProgress', 'In Progress')}
            </div>
          </div>
        </div>

        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 flex items-center gap-3">
          <div className="p-2 bg-red-100 dark:bg-red-900/40 rounded-lg">
            <XCircle size={18} className="text-red-600" />
          </div>
          <div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">{stats.cancelled}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              {t('staffDashboard.cancelled', 'Cancelled')}
            </div>
          </div>
        </div>

        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 flex items-center gap-3">
          <div className="p-2 bg-gray-100 dark:bg-gray-700 rounded-lg">
            <User size={18} className="text-gray-600" />
          </div>
          <div>
            <div className="text-xl font-bold text-gray-900 dark:text-white">{stats.noShows}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              {t('staffDashboard.noShows', 'No-Shows')}
            </div>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Link
          to="/my-schedule"
          className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 hover:border-brand-500 dark:hover:border-brand-400 transition-colors group"
        >
          <div className="flex items-center gap-4">
            <div className="p-3 bg-brand-100 dark:bg-brand-900/40 rounded-lg group-hover:bg-brand-200 dark:group-hover:bg-brand-800/40 transition-colors">
              <CalendarDays size={24} className="text-brand-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {t('staffDashboard.viewMySchedule', 'View My Schedule')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('staffDashboard.viewScheduleDesc', 'See your daily appointments and manage your time')}
              </p>
            </div>
            <ArrowRight size={20} className="text-gray-400 group-hover:text-brand-500 ml-auto transition-colors" />
          </div>
        </Link>

        <Link
          to="/my-availability"
          className="p-5 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 hover:border-brand-500 dark:hover:border-brand-400 transition-colors group"
        >
          <div className="flex items-center gap-4">
            <div className="p-3 bg-green-100 dark:bg-green-900/40 rounded-lg group-hover:bg-green-200 dark:group-hover:bg-green-800/40 transition-colors">
              <CalendarOff size={24} className="text-green-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {t('staffDashboard.manageAvailability', 'Manage Availability')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('staffDashboard.availabilityDesc', 'Set your working hours and time off')}
              </p>
            </div>
            <ArrowRight size={20} className="text-gray-400 group-hover:text-green-500 ml-auto transition-colors" />
          </div>
        </Link>
      </div>
    </div>
  );
};

export default StaffDashboard;
