import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  LineChart,
  Line
} from 'recharts';
import { TrendingUp, TrendingDown, Minus } from 'lucide-react';
import { useServices } from '../hooks/useServices';
import { useResources } from '../hooks/useResources';
import { useAppointments } from '../hooks/useAppointments';
import { useCustomers } from '../hooks/useCustomers';
import QuickAddAppointment from '../components/QuickAddAppointment';

interface Metric {
  label: string;
  value: string;
  trend: 'up' | 'down' | 'neutral';
  change: string;
}

const Dashboard: React.FC = () => {
  const { t } = useTranslation();
  const { data: services, isLoading: servicesLoading } = useServices();
  const { data: resources, isLoading: resourcesLoading } = useResources();
  const { data: appointments, isLoading: appointmentsLoading } = useAppointments();
  const { data: customers, isLoading: customersLoading } = useCustomers();

  const isLoading = servicesLoading || resourcesLoading || appointmentsLoading || customersLoading;

  // Calculate metrics from real data
  const metrics: Metric[] = useMemo(() => {
    if (!appointments || !customers || !services || !resources) {
      return [
        { label: t('dashboard.totalAppointments'), value: '0', trend: 'neutral', change: '0%' },
        { label: t('customers.title'), value: '0', trend: 'neutral', change: '0%' },
        { label: t('services.title'), value: '0', trend: 'neutral', change: '0%' },
        { label: t('resources.title'), value: '0', trend: 'neutral', change: '0%' },
      ];
    }

    const activeCustomers = customers.filter(c => c.status === 'Active').length;

    return [
      { label: t('dashboard.totalAppointments'), value: appointments.length.toString(), trend: 'up', change: '+12%' },
      { label: t('customers.title'), value: activeCustomers.toString(), trend: 'up', change: '+8%' },
      { label: t('services.title'), value: services.length.toString(), trend: 'neutral', change: '0%' },
      { label: t('resources.title'), value: resources.length.toString(), trend: 'up', change: '+3%' },
    ];
  }, [appointments, customers, services, resources, t]);

  // Calculate weekly data from appointments
  const weeklyData = useMemo(() => {
    if (!appointments) {
      return [
        { name: 'Mon', revenue: 0, appointments: 0 },
        { name: 'Tue', revenue: 0, appointments: 0 },
        { name: 'Wed', revenue: 0, appointments: 0 },
        { name: 'Thu', revenue: 0, appointments: 0 },
        { name: 'Fri', revenue: 0, appointments: 0 },
        { name: 'Sat', revenue: 0, appointments: 0 },
        { name: 'Sun', revenue: 0, appointments: 0 },
      ];
    }

    // Group appointments by day of week
    const dayMap: { [key: string]: { revenue: number; count: number } } = {
      'Mon': { revenue: 0, count: 0 },
      'Tue': { revenue: 0, count: 0 },
      'Wed': { revenue: 0, count: 0 },
      'Thu': { revenue: 0, count: 0 },
      'Fri': { revenue: 0, count: 0 },
      'Sat': { revenue: 0, count: 0 },
      'Sun': { revenue: 0, count: 0 },
    };

    appointments.forEach(appt => {
      const date = new Date(appt.startTime);
      const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      const dayName = dayNames[date.getDay()];

      dayMap[dayName].count++;
      // Use price from appointment or default to 0
      dayMap[dayName].revenue += appt.price || 0;
    });

    return [
      { name: 'Mon', revenue: dayMap['Mon'].revenue, appointments: dayMap['Mon'].count },
      { name: 'Tue', revenue: dayMap['Tue'].revenue, appointments: dayMap['Tue'].count },
      { name: 'Wed', revenue: dayMap['Wed'].revenue, appointments: dayMap['Wed'].count },
      { name: 'Thu', revenue: dayMap['Thu'].revenue, appointments: dayMap['Thu'].count },
      { name: 'Fri', revenue: dayMap['Fri'].revenue, appointments: dayMap['Fri'].count },
      { name: 'Sat', revenue: dayMap['Sat'].revenue, appointments: dayMap['Sat'].count },
      { name: 'Sun', revenue: dayMap['Sun'].revenue, appointments: dayMap['Sun'].count },
    ];
  }, [appointments]);

  if (isLoading) {
    return (
      <div className="p-8 space-y-8">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('dashboard.title')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('common.loading')}</p>
        </div>
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="p-6 bg-white dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-xl shadow-sm 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-8">
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('dashboard.title')}</h2>
        <p className="text-gray-500 dark:text-gray-400">{t('dashboard.todayOverview')}</p>
      </div>

      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
        {metrics.map((metric, index) => (
          <div key={index} className="p-6 bg-white dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-xl shadow-sm transition-colors duration-200">
            <p className="text-sm font-medium text-gray-500 dark:text-gray-400">{metric.label}</p>
            <div className="flex items-baseline gap-2 mt-2">
              <span className="text-2xl font-bold text-gray-900 dark:text-white">{metric.value}</span>
              <span className={`flex items-center text-xs font-medium px-2 py-0.5 rounded-full ${
                metric.trend === 'up' ? 'text-green-700 bg-green-50 dark:bg-green-900/30 dark:text-green-400' : 
                metric.trend === 'down' ? 'text-red-700 bg-red-50 dark:bg-red-900/30 dark:text-red-400' : 'text-gray-700 bg-gray-50 dark:bg-gray-700 dark:text-gray-300'
              }`}>
                {metric.trend === 'up' && <TrendingUp size={12} className="mr-1" />}
                {metric.trend === 'down' && <TrendingDown size={12} className="mr-1" />}
                {metric.trend === 'neutral' && <Minus size={12} className="mr-1" />}
                {metric.change}
              </span>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Quick Add Appointment */}
        <div className="lg:col-span-1">
          <QuickAddAppointment />
        </div>

        {/* Revenue Chart */}
        <div className="lg:col-span-2 p-6 bg-white dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-xl shadow-sm transition-colors duration-200">
          <h3 className="mb-6 text-lg font-semibold text-gray-900 dark:text-white">{t('dashboard.totalRevenue')}</h3>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={weeklyData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#374151" strokeOpacity={0.2} />
                <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#9CA3AF' }} />
                <YAxis axisLine={false} tickLine={false} tickFormatter={(value) => `$${value}`} tick={{ fill: '#9CA3AF' }} />
                <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'
                  }}
                />
                <Bar dataKey="revenue" fill="#3b82f6" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Appointments Chart - Full Width */}
      <div className="p-6 bg-white dark:bg-gray-800 border border-gray-100 dark:border-gray-700 rounded-xl shadow-sm transition-colors duration-200">
        <h3 className="mb-6 text-lg font-semibold text-gray-900 dark:text-white">{t('dashboard.upcomingAppointments')}</h3>
        <div className="h-64">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={weeklyData}>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#374151" strokeOpacity={0.2} />
              <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#9CA3AF' }} />
              <YAxis axisLine={false} tickLine={false} tick={{ fill: '#9CA3AF' }} />
              <Tooltip
                contentStyle={{
                  borderRadius: '8px',
                  border: 'none',
                  boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)',
                  backgroundColor: '#1F2937',
                  color: '#F3F4F6'
                }}
              />
              <Line type="monotone" dataKey="appointments" stroke="#10b981" strokeWidth={3} dot={{ r: 4, fill: '#10b981' }} />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;