import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import {
  UserGroupIcon,
  HeartIcon,
  BuildingOffice2Icon,
  CalendarDaysIcon,
  CreditCardIcon,
  ChatBubbleLeftEllipsisIcon,
  BanknotesIcon,
  ArrowPathIcon,
  UserPlusIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { formatNumber, formatRial, formatDateTime } from '../lib/utils';

interface DashboardStats {
  total_users: number;
  active_doctors: number;
  total_doctors: number;
  total_clinics: number;
  today_appointments: number;
  total_appointments: number;
  today_payments_count: number;
  today_payments_amount: number;
  total_payments_amount: number;
  pending_comments: number;
  pending_settlements: number;
}

interface RecentAppointment {
  uuid: string;
  slot_start: string;
  status: string;
  doctor_name: string;
  user_mobile: string;
  user_name: string | null;
  created_at: string;
}

interface RecentPayment {
  uuid: string;
  amount: number;
  status: string;
  gateway: string;
  user_mobile: string;
  user_name: string | null;
  created_at: string;
}

interface RecentUser {
  uuid: string;
  mobile: string;
  name: string | null;
  email: string | null;
  created_at: string;
}

interface RecentData {
  appointments: RecentAppointment[];
  payments: RecentPayment[];
  users: RecentUser[];
}

const APPT_STATUS: Record<string, { label: string; cls: string }> = {
  waiting_for_payment: { label: 'انتظار پرداخت', cls: 'bg-yellow-100 dark:bg-yellow-400/10 text-yellow-700 dark:text-yellow-300' },
  reserved:            { label: 'رزرو شده',      cls: 'bg-blue-100 dark:bg-blue-400/10 text-blue-700 dark:text-blue-300' },
  checked_in:          { label: 'ورود به مطب',   cls: 'bg-indigo-100 dark:bg-indigo-400/10 text-indigo-700 dark:text-indigo-300' },
  waiting:             { label: 'صف انتظار',     cls: 'bg-orange-100 dark:bg-orange-400/10 text-orange-700 dark:text-orange-300' },
  in_progress:         { label: 'در حال ویزیت',  cls: 'bg-purple-100 dark:bg-purple-400/10 text-purple-700 dark:text-purple-300' },
  visited:             { label: 'ویزیت شده',     cls: 'bg-emerald-100 dark:bg-emerald-400/10 text-emerald-700 dark:text-emerald-300' },
  completed:           { label: 'تکمیل شده',     cls: 'bg-green-100 dark:bg-green-400/10 text-green-700 dark:text-green-300' },
  cancelled_by_doctor: { label: 'لغو پزشک',      cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300' },
  cancelled_by_user:   { label: 'لغو بیمار',     cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300' },
  auto_cancel_unpaid:  { label: 'لغو خودکار',    cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600 dark:text-slate-400' },
  no_show:             { label: 'غیبت',           cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600 dark:text-slate-400' },
};

const PAY_STATUS: Record<string, { label: string; cls: string }> = {
  pending:  { label: 'در انتظار', cls: 'bg-yellow-100 dark:bg-yellow-400/10 text-yellow-700 dark:text-yellow-300' },
  received: { label: 'موفق',      cls: 'bg-green-100 dark:bg-green-400/10 text-green-700 dark:text-green-300' },
  canceled: { label: 'لغو شده',   cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300' },
  refund:   { label: 'استرداد',   cls: 'bg-blue-100 dark:bg-blue-400/10 text-blue-700 dark:text-blue-300' },
};

function MicroBadge({ status, map }: { status: string; map: Record<string, { label: string; cls: string }> }) {
  const s = map[status] ?? { label: status, cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600 dark:text-slate-400' };
  return (
    <span className={`shrink-0 text-[10px] font-medium px-2 py-0.5 rounded-full ${s.cls}`}>{s.label}</span>
  );
}

interface StatCard {
  label: string;
  value: string;
  sub?: string;
  icon: React.ElementType;
  iconBg: string;
  iconColor: string;
}

function StatCardSkeleton() {
  return (
    <div className="cp-card p-5 flex items-start gap-4">
      <div className="w-11 h-11 rounded-xl skeleton shrink-0" />
      <div className="flex-1 space-y-2 pt-0.5">
        <div className="h-3 rounded skeleton w-2/3" />
        <div className="h-6 rounded skeleton w-1/2" />
        <div className="h-3 rounded skeleton w-3/4" />
      </div>
    </div>
  );
}

function RecentSkeleton() {
  return (
    <div className="space-y-3 mt-1">
      {[...Array(4)].map((_, i) => (
        <div key={i} className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-full skeleton shrink-0" />
          <div className="flex-1 space-y-1.5">
            <div className="h-3 rounded skeleton w-3/4" />
            <div className="h-3 rounded skeleton w-1/2" />
          </div>
        </div>
      ))}
    </div>
  );
}

export default function DashboardPage() {
  const statsQ = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: () => api.get<ApiResponse<DashboardStats>>('/api/v1/admin/dashboard/stats'),
    staleTime: 60_000,
  });

  const recentQ = useQuery({
    queryKey: ['dashboard-recent'],
    queryFn: () => api.get<ApiResponse<RecentData>>('/api/v1/admin/dashboard/recent'),
    staleTime: 30_000,
  });

  const stats: DashboardStats | undefined = (statsQ.data?.data as any)?.data ?? statsQ.data?.data;
  const recent: RecentData | undefined   = (recentQ.data?.data as any)?.data ?? recentQ.data?.data;
  const fn = (n?: number) => (n !== undefined ? formatNumber(n) : '—');

  const cards: StatCard[] = [
    { label: 'کل کاربران',       value: fn(stats?.total_users),          icon: UserGroupIcon,             iconBg: 'bg-violet-100 dark:bg-violet-400/10', iconColor: 'text-violet-600 dark:text-violet-400' },
    { label: 'پزشکان فعال',      value: fn(stats?.active_doctors),       sub: stats ? `از ${fn(stats.total_doctors)} پزشک` : undefined, icon: HeartIcon, iconBg: 'bg-emerald-100 dark:bg-emerald-400/10', iconColor: 'text-emerald-600 dark:text-emerald-400' },
    { label: 'کلینیک‌ها',        value: fn(stats?.total_clinics),        icon: BuildingOffice2Icon,       iconBg: 'bg-blue-100 dark:bg-blue-400/10',    iconColor: 'text-blue-600 dark:text-blue-400' },
    { label: 'نوبت‌های امروز',   value: fn(stats?.today_appointments),   sub: stats ? `مجموع: ${fn(stats.total_appointments)}` : undefined, icon: CalendarDaysIcon, iconBg: 'bg-orange-100 dark:bg-orange-400/10', iconColor: 'text-orange-600 dark:text-orange-400' },
    { label: 'درآمد امروز',      value: stats?.today_payments_amount !== undefined ? formatRial(stats.today_payments_amount) : '—', sub: stats ? `${fn(stats.today_payments_count)} تراکنش` : undefined, icon: CreditCardIcon, iconBg: 'bg-pink-100 dark:bg-pink-400/10', iconColor: 'text-pink-600 dark:text-pink-400' },
    { label: 'کل درآمد',         value: stats?.total_payments_amount !== undefined ? formatRial(stats.total_payments_amount) : '—', icon: CreditCardIcon, iconBg: 'bg-indigo-100 dark:bg-indigo-400/10', iconColor: 'text-indigo-600 dark:text-indigo-400' },
    { label: 'نظرات در انتظار',  value: fn(stats?.pending_comments),     icon: ChatBubbleLeftEllipsisIcon, iconBg: 'bg-yellow-100 dark:bg-yellow-400/10', iconColor: 'text-yellow-600 dark:text-yellow-400' },
    { label: 'درخواست تسویه',    value: fn(stats?.pending_settlements),  icon: BanknotesIcon,             iconBg: 'bg-teal-100 dark:bg-teal-400/10',    iconColor: 'text-teal-600 dark:text-teal-400' },
  ];

  return (
    <div className="animate-slide-up">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-slate-900 dark:text-slate-50">داشبورد</h1>
          <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">خلاصه وضعیت سیستم</p>
        </div>
        {statsQ.isError && (
          <button onClick={() => statsQ.refetch()} className="flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors">
            <ArrowPathIcon className="w-4 h-4" />
            تلاش مجدد
          </button>
        )}
      </div>

      {statsQ.isError && (
        <div className="mb-5 cp-card border-red-200 dark:border-red-500/20 bg-red-50 dark:bg-red-500/5 px-4 py-3 text-sm text-red-600 dark:text-red-400">
          خطا در دریافت آمار — اطلاعات ممکن است به‌روز نباشند.
        </div>
      )}

      {/* Stats grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statsQ.isLoading
          ? Array.from({ length: 8 }).map((_, i) => <StatCardSkeleton key={i} />)
          : cards.map((c) => (
            <div key={c.label} className="cp-card p-5 flex items-start gap-4">
              <div className={`cp-stat-icon ${c.iconBg}`}>
                <c.icon className={`w-5 h-5 ${c.iconColor}`} />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">{c.label}</p>
                <p className="text-xl font-bold text-slate-900 dark:text-slate-50 leading-none">{c.value}</p>
                {c.sub && <p className="text-xs text-slate-400 dark:text-slate-500 mt-1.5">{c.sub}</p>}
              </div>
            </div>
          ))
        }
      </div>

      {/* Recent activities */}
      <div className="mt-5 grid grid-cols-1 lg:grid-cols-3 gap-4">

        {/* Recent Appointments */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">آخرین نوبت‌ها</h3>
            <Link to="/admin/appointments" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">مشاهده همه</Link>
          </div>
          {recentQ.isLoading ? <RecentSkeleton /> : recentQ.isError ? (
            <p className="text-center py-6 text-sm text-slate-400">خطا در دریافت اطلاعات</p>
          ) : !recent?.appointments?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">نوبتی ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.appointments.map((a) => (
                <li key={a.uuid}>
                  <Link to={`/admin/appointments/${a.uuid}`} className="flex items-start justify-between gap-2 group">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {a.user_name || a.user_mobile}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 truncate">دکتر {a.doctor_name}</p>
                      <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-0.5">{formatDateTime(a.slot_start)}</p>
                    </div>
                    <MicroBadge status={a.status} map={APPT_STATUS} />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* Recent Payments */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">آخرین پرداخت‌ها</h3>
            <Link to="/admin/payments" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">مشاهده همه</Link>
          </div>
          {recentQ.isLoading ? <RecentSkeleton /> : recentQ.isError ? (
            <p className="text-center py-6 text-sm text-slate-400">خطا در دریافت اطلاعات</p>
          ) : !recent?.payments?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">پرداختی ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.payments.map((p) => (
                <li key={p.uuid}>
                  <Link to={`/admin/payments/${p.uuid}`} className="flex items-start justify-between gap-2 group">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {p.user_name || p.user_mobile}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400">{formatRial(p.amount)}</p>
                      <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-0.5">{formatDateTime(p.created_at)}</p>
                    </div>
                    <MicroBadge status={p.status} map={PAY_STATUS} />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* Recent Users */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">کاربران جدید</h3>
            <Link to="/admin/users" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">مشاهده همه</Link>
          </div>
          {recentQ.isLoading ? <RecentSkeleton /> : recentQ.isError ? (
            <p className="text-center py-6 text-sm text-slate-400">خطا در دریافت اطلاعات</p>
          ) : !recent?.users?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">کاربری ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.users.map((u) => (
                <li key={u.uuid}>
                  <Link to={`/admin/users/${u.uuid}`} className="flex items-center gap-3 group">
                    <div className="w-8 h-8 rounded-full bg-violet-100 dark:bg-violet-400/10 flex items-center justify-center shrink-0">
                      <UserPlusIcon className="w-4 h-4 text-violet-600 dark:text-violet-400" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {u.name || u.mobile}
                      </p>
                      {u.name && <p className="text-xs text-slate-500 dark:text-slate-400 truncate" dir="ltr">{u.mobile}</p>}
                      <p className="text-[11px] text-slate-400 dark:text-slate-500">{formatDateTime(u.created_at)}</p>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

      </div>
    </div>
  );
}
