'use client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { Calendar, ChevronRight, Pill, TrendingUp, User, Users } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';

interface Patient {
  _id: string;
  userId: {
    firstName: string;
    lastName: string;
  };
  gender?: string;
  dateOfBirth?: string;
}

interface Appointment {
  _id: string;
  patientId?: {
    userId?: {
      firstName: string;
      lastName: string;
    }
  } | null;
  doctorId?: {
    userId?: {
      firstName: string;
      lastName: string;
    }
  };
  appointmentDate: string;
  status: string;
}

interface Doctor {
  _id: string;
  userId: {
    firstName: string;
    lastName: string;
  };
  specialization?: string;
  licenseNumber?: string;
}

export default function DashboardPage() {
  const { t } = useLanguage();
  const { token, user } = useAuthStore();
  const [statsData, setStatsData] = useState({
    patients: 0,
    appointments: 0,
    prescriptions: 0,
    doctors: 0,
    growth: 0
  });



  const [recentPatients, setRecentPatients] = useState<Patient[]>([]);
  const [upcomingAppointments, setUpcomingAppointments] = useState<Appointment[]>([]);
  const [recentDoctors, setRecentDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(true);
  const isDentist = user?.userType === 'dentist';
  const isAdmin = user?.userType === 'admin';

  const getLocalizedGender = (gender?: string) => {
    if (!gender) return t('common.na');
    const normalized = gender.toLowerCase();
    if (normalized === 'male') return t('common.male');
    if (normalized === 'female') return t('common.female');
    if (normalized === 'other') return t('common.other');
    return gender;
  };

  const getLocalizedAppointmentStatus = (status: string) => {
    const key = status.toLowerCase();
    const translated = t(`appointments.${key}`);
    return translated === `appointments.${key}` ? status : translated;
  };

  useEffect(() => {
    const fetchStats = async () => {
      if (!token) return;

      const response = await api.dashboard.getStats(token);
      if (response.success && response.data) {
        setStatsData(response.data);
      }

      const patientsResponse = await api.patients.get({ limit: 5 });
      if (patientsResponse.success && patientsResponse.data) {
        setRecentPatients(patientsResponse.data);
      }

      const appointmentsResponse = await api.appointments.get(token, { limit: 5, upcoming: true });
      if (appointmentsResponse.success && appointmentsResponse.data) {
        setUpcomingAppointments(appointmentsResponse.data);
      }

      if (isAdmin) {
        const doctorsResponse = await api.doctors.get(token, { limit: 5 });
        if (doctorsResponse.success && doctorsResponse.data) {
          setRecentDoctors(doctorsResponse.data);
        }
      }

      setLoading(false);
    };

    fetchStats();
  }, [token, isAdmin]);

  const stats = [
    ...(isAdmin ? [
      {
        titleKey: 'doctors.title',
        value: loading ? '-' : statsData.doctors.toString(),
        icon: Users,
        color: 'bg-purple-500'
      }
    ] : [
      {
        titleKey: 'patients.title',
        value: loading ? '-' : statsData.patients.toString(),
        icon: Users,
        color: 'bg-teal-500'
      }
    ]),
    ...(isAdmin ? [] : [{
      titleKey: 'appointments.appointmentDate',
      value: loading ? '-' : statsData.appointments.toString(),
      icon: Calendar,
      color: 'bg-cyan-500'
    }]),
    ...(isAdmin ? [] : [{
      titleKey: 'prescriptions.title',
      value: loading ? '-' : statsData.prescriptions.toString(),
      icon: Pill,
      color: 'bg-blue-500'
    }]),
    {
      titleKey: 'dashboard.growth',
      value: loading ? '-' : `${statsData.growth > 0 ? '+' : ''}${statsData.growth}%`,
      icon: TrendingUp,
      color: 'bg-teal-600'
    },
  ];

  return (
    <div className="space-y-8">
      <div className="border-b border-gray-200 pb-6">
        <h1 className="text-4xl font-bold text-gray-900">{t('navigation.dashboard')}</h1>
        <p className="text-gray-600 mt-2">{t('messages.welcome')}.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {stats.map((stat) => {
          const Icon = stat.icon;
          return (
            <Card key={stat.titleKey} className="border-gray-200 hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0">
                <CardTitle className="text-sm font-medium text-gray-600">{t(stat.titleKey)}</CardTitle>
                <div className={`${stat.color} p-3 rounded-lg`}>
                  <Icon className="h-5 w-5 text-white" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-gray-900">{stat.value}</div>
                <p className="text-xs text-gray-500 mt-2">{t('dashboard.vsLastMonth')}</p>
              </CardContent>
            </Card>
          );
        })}
      </div>

      <div className={`grid gap-6 ${isAdmin || isDentist ? 'grid-cols-1' : 'grid-cols-1 lg:grid-cols-3'}`}>
        {isAdmin ? (
          <div className="lg:col-span-2">
            <Card className="border-gray-200 h-full">
              <CardHeader className="flex flex-row items-center justify-between">
                <CardTitle>{t('doctors.title')}</CardTitle>
                <Link href="/doctors">
                  <Button variant="ghost" size="sm" className="text-primary gap-1">
                    {t('common.viewAll')}
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </Link>
              </CardHeader>
              <CardContent>
                {recentDoctors.length > 0 ? (
                  <div className="space-y-4">
                    {recentDoctors.map((doctor) => (
                      <div key={doctor._id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                        <div className="flex items-center gap-3">
                          <div className="bg-purple-500/10 p-2 rounded-full">
                            <User className="h-5 w-5 text-purple-500" />
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">
                              {doctor.userId.firstName} {doctor.userId.lastName}
                            </p>
                            <p className="text-xs text-gray-500">
                              {doctor.specialization || t('common.na')}
                            </p>
                          </div>
                        </div>
                        <Link href="/doctors">
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-400 hover:text-purple-500">
                            <ChevronRight className="h-4 w-4" />
                          </Button>
                        </Link>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12">
                    <p className="text-gray-400 mb-2">{t('common.noData')}</p>
                    <p className="text-sm text-gray-500">{t('doctors.noDoctors')}</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        ) : !isAdmin && (
          <div className={isDentist ? "lg:col-span-3" : "lg:col-span-2"}>
            <Card className="border-gray-200 h-full">
              <CardHeader className="flex flex-row items-center justify-between">
                <CardTitle>{t('patients.title')}</CardTitle>
                <Link href="/patients">
                  <Button variant="ghost" size="sm" className="text-primary gap-1">
                    {t('common.viewAll')}
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </Link>
              </CardHeader>
              <CardContent>
                {recentPatients.length > 0 ? (
                  <div className="space-y-4">
                    {recentPatients.map((patient) => (
                      <div key={patient._id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                        <div className="flex items-center gap-3">
                          <div className="bg-primary/10 p-2 rounded-full">
                            <User className="h-5 w-5 text-primary" />
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">
                              {patient.userId.firstName} {patient.userId.lastName}
                            </p>
                            <p className="text-xs text-gray-500">
                              {getLocalizedGender(patient.gender)} • {patient.dateOfBirth
                                ? `${new Date().getFullYear() - new Date(patient.dateOfBirth).getFullYear()} ${t('dashboard.years')}`
                                : t('dashboard.ageNA')}
                            </p>
                          </div>
                        </div>
                        <Link href={`/patients`}>
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-400 hover:text-primary">
                            <ChevronRight className="h-4 w-4" />
                          </Button>
                        </Link>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12">
                    <p className="text-gray-400 mb-2">{t('common.noData')}</p>
                    <p className="text-sm text-gray-500">{t('patients.noPatients')}</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        )}

        {!isDentist && !isAdmin && (
          <Card className="border-gray-200 h-full">
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{t('appointments.upcomingAppointments')}</CardTitle>
              <Link href="/appointments">
                <Button variant="ghost" size="sm" className="text-primary gap-1">
                  {t('common.viewAll')}
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </Link>
            </CardHeader>
            <CardContent>
              {upcomingAppointments.length > 0 ? (
                <div className="space-y-4">
                  {upcomingAppointments.map((appointment) => (
                    <div key={appointment._id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                      <div className="flex items-center gap-3">
                        <div className="bg-blue-500/10 p-2 rounded-full">
                          <Calendar className="h-5 w-5 text-blue-600" />
                        </div>
                        <div>
                          <p className="font-medium text-gray-900">
                            {appointment.patientId?.userId?.firstName && appointment.patientId?.userId?.lastName
                              ? `${appointment.patientId.userId.firstName} ${appointment.patientId.userId.lastName}`
                              : t('dashboard.patientDeleted')}
                          </p>
                          <p className="text-xs text-gray-500">
                            {new Date(appointment.appointmentDate).toLocaleString()}
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                          {getLocalizedAppointmentStatus(appointment.status)}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-12">
                  <p className="text-gray-400 mb-2">{t('appointments.noAppointments')}</p>
                  <p className="text-sm text-gray-500">{t('appointments.upcomingAppointments')}</p>
                </div>
              )}
            </CardContent>
          </Card>)}      </div>
    </div>
  );
}
