'use client';

import { useState, useEffect, useCallback } from 'react';
import DashboardShell from '../components/DashboardShell';
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, BarChart, Bar,
} from 'recharts';
import { Skeleton } from 'primereact/skeleton';

// ─── Types ───────────────────────────────────────────────────────────────────

type PeriodKey = 'week' | 'month' | '3_months' | '6_months' | 'year';

interface SummaryMetric {
  value: number;
  unit?: string;
  change_percent?: number;
  change_absolute?: number;
  trend?: 'up' | 'down' | 'neutral';
  max?: number;
  currency?: string;
}

interface WeeklyTrip {
  day: string;
  label_ar: string;
  label_en: string;
  date: string;
  completed: number;
  cancelled: number;
  total: number;
}

interface RevenueSeries {
  key: string;
  label_ar: string;
  label_en: string;
  from: string;
  to: string;
  amount: number;
}

interface TopCaptain {
  rank: number;
  id: number;
  name: string;
  image: string;
  trips_count: number;
  rating: number;
  revenue: number;
  currency: string;
}

interface ReportData {
  period: string;
  window: { from: string; to: string; previous_from: string; previous_to: string };
  summary: {
    completion_rate: SummaryMetric;
    average_rating: SummaryMetric;
    total_trips: SummaryMetric;
    total_revenue: SummaryMetric;
  };
  weekly_trips: WeeklyTrip[];
  revenue_series: RevenueSeries[];
  top_captains: TopCaptain[];
}

// ─── Period Config ────────────────────────────────────────────────────────────

const PERIODS: { label: string; value: PeriodKey }[] = [
  { label: 'أسبوع',   value: 'week' },
  { label: 'شهر',     value: 'month' },
  { label: '3 أشهر',  value: '3_months' },
  { label: '6 أشهر',  value: '6_months' },
  { label: 'سنة',     value: 'year' },
];

// ─── Skeleton Components ──────────────────────────────────────────────────────

function KpiSkeleton() {
  return (
    <div className="grid grid-cols-4 gap-4 mb-6">
      {[...Array(4)].map((_, i) => (
        <div
          key={i}
          className="bg-white rounded-2xl p-5"
          style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
        >
          <div className="flex items-center justify-between mb-3">
            <Skeleton shape="rectangle" size="2.5rem" borderRadius="12px" />
            <Skeleton width="3rem" height="1.25rem" borderRadius="999px" />
          </div>
          <Skeleton width="7rem" height="1.75rem" className="mb-1" borderRadius="8px" />
          <Skeleton width="5rem" height="0.85rem" borderRadius="8px" />
        </div>
      ))}
    </div>
  );
}

function ChartSkeleton({ title, subtitle, iconBg, iconColor, icon }: {
  title: string; subtitle: string; iconBg: string; iconColor: string; icon: string;
}) {
  return (
    <div
      className="bg-white rounded-2xl p-5"
      style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
    >
      <div className="flex items-center justify-between mb-4">
        <div>
          <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{title}</h3>
          <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{subtitle}</p>
        </div>
        <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: iconBg }}>
          <i className={`${icon} text-base`} style={{ color: iconColor }}></i>
        </div>
      </div>
      <Skeleton width="100%" height="200px" borderRadius="12px" />
    </div>
  );
}

function TableSkeleton() {
  return (
    <div
      className="bg-white rounded-2xl overflow-hidden"
      style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
    >
      <div className="flex items-center gap-2 px-6 py-4 border-b" style={{ borderColor: '#F1F5F9' }}>
        <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#FEF3C7' }}>
          <i className="ri-medal-fill text-base" style={{ color: '#D97706' }}></i>
        </div>
        <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>أفضل السائقين أداءً</h3>
      </div>
      <div className="p-4 space-y-3">
        {[...Array(5)].map((_, i) => (
          <div key={i} className="flex items-center gap-4 px-2 py-1">
            <Skeleton shape="rectangle" size="1.75rem" borderRadius="10px" />
            <Skeleton shape="circle" size="2.25rem" />
            <Skeleton width="7rem" height="1rem" borderRadius="6px" />
            <Skeleton width="3.5rem" height="1rem" borderRadius="6px" className="mr-auto" />
            <Skeleton width="3rem" height="1rem" borderRadius="6px" />
            <Skeleton width="5rem" height="1rem" borderRadius="6px" />
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function ReportsPage() {
  const [period, setPeriod] = useState<PeriodKey>('week');
  const [report, setReport] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Read auth from localStorage (matches useApi pattern)
  const getAuthHeaders = useCallback((): Record<string, string> => {
    const headers: Record<string, string> = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'x-api-key': '5f43766dcd92b8c3e7639d2a8791063c',
    };

    if (typeof window !== 'undefined') {
      try {
        const raw = window.localStorage.getItem('sast-auth');
        if (raw) {
          const parsed = JSON.parse(raw) as { state?: Record<string, unknown> };
          const state = parsed?.state;
          if (state) {
            if (typeof state.token === 'string') headers['Authorization'] = `Bearer ${state.token}`;
            if (typeof state.country_code === 'string') headers['X-Country-Code'] = state.country_code;
            if (typeof state.device_id === 'string') headers['X-Device-Id'] = state.device_id;
          }
        }
      } catch {
        // ignore
      }
    }

    return headers;
  }, []);

  const fetchReport = useCallback(async (p: PeriodKey) => {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch(
        `https://sast.4hoste.com/api/v1/company/reports/overview?period=${p}`,
        { method: 'GET', headers: getAuthHeaders() },
      );

      const json = (await res.json().catch(() => null)) as {
        key?: string;
        msg?: string;
        data?: ReportData;
      } | null;

      if (!res.ok || !json?.data) {
        const msg =
          (json as Record<string, unknown>)?.msg as string ||
          (json as Record<string, unknown>)?.message as string ||
          `HTTP ${res.status}`;
        setError(msg);
        setReport(null);
      } else {
        setReport(json.data);
      }
    } catch (err) {
      const m = err instanceof Error ? err.message : 'حدث خطأ أثناء الاتصال بالخادم.';
      setError(m);
      setReport(null);
    } finally {
      setLoading(false);
    }
  }, [getAuthHeaders]);

  // Fetch on mount & period change
  useEffect(() => {
    fetchReport(period);
  }, [period, fetchReport]);

  // ── Derived data ──────────────────────────────────────────────────────────

  const kpiCards = report
    ? [
        {
          label: 'إجمالي الإيرادات',
          value: `${report.summary.total_revenue.value.toLocaleString('ar-SA')} ر`,
          change: `+${report.summary.total_revenue.change_percent}%`,
          icon: 'ri-money-dollar-circle-fill',
          color: '#059669',
          bg: '#DCFCE7',
        },
        {
          label: 'إجمالي الرحلات',
          value: report.summary.total_trips.value.toLocaleString('ar-SA'),
          change: `+${report.summary.total_trips.change_percent}%`,
          icon: 'ri-route-fill',
          color: '#1E3A8A',
          bg: '#EEF2FF',
        },
        {
          label: 'متوسط التقييم',
          value: `${report.summary.average_rating.value} ⭐`,
          change: `+${report.summary.average_rating.change_absolute}`,
          icon: 'ri-star-fill',
          color: '#D97706',
          bg: '#FEF3C7',
        },
        {
          label: 'نسبة الالتزام',
          value: `${report.summary.completion_rate.value}%`,
          change: `+${report.summary.completion_rate.change_percent}%`,
          icon: 'ri-time-fill',
          color: '#7C3AED',
          bg: '#EDE9FE',
        },
      ]
    : [];

  const revenueChartData = report?.revenue_series.map((r) => ({
    month: r.label_ar,
    revenue: r.amount,
  })) ?? [];

  const tripsChartData = report?.weekly_trips.map((t) => ({
    day: t.label_ar,
    completed: t.completed,
    cancelled: t.cancelled,
    total: t.total,
  })) ?? [];

  // ── Render ────────────────────────────────────────────────────────────────

  return (
    <DashboardShell title="التقارير والإحصائيات" subtitle="تحليل شامل لأداء الشركة">

      {/* Period Filter */}
      <div className="flex items-center gap-2 mb-6">
        {PERIODS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => setPeriod(value)}
            disabled={loading}
            className="px-4 py-2 rounded-xl text-sm font-bold cursor-pointer transition-all whitespace-nowrap disabled:opacity-50"
            style={{
              background: period === value ? '#1E3A8A' : 'white',
              color: period === value ? 'white' : '#64748b',
              border: `1px solid ${period === value ? '#1E3A8A' : '#E2E8F0'}`,
              fontFamily: '"IBM Plex Sans Arabic", sans-serif',
            }}
          >
            {label}
          </button>
        ))}
        <button
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold cursor-pointer whitespace-nowrap mr-auto"
          style={{ background: '#F1F5F9', color: '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
        >
          <i className="ri-download-2-line text-base"></i>
          تصدير التقرير
        </button>
      </div>

      {/* Error State */}
      {error && !loading && (
        <div
          className="flex items-center gap-3 px-5 py-4 rounded-2xl mb-6 text-sm"
          style={{ background: '#FEF2F2', border: '1px solid #FECACA', color: '#DC2626', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
        >
          <i className="ri-error-warning-fill text-base"></i>
          <span>{error}</span>
          <button
            onClick={() => fetchReport(period)}
            className="mr-auto font-bold underline"
            style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
          >
            إعادة المحاولة
          </button>
        </div>
      )}

      {/* ── KPI Cards ── */}
      {loading ? (
        <KpiSkeleton />
      ) : report ? (
        <div className="grid grid-cols-4 gap-4 mb-6">
          {kpiCards.map((k, i) => (
            <div
              key={i}
              className="bg-white rounded-2xl p-5"
              style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}
            >
              <div className="flex items-center justify-between mb-3">
                <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: k.bg }}>
                  <i className={`${k.icon} text-xl`} style={{ color: k.color }}></i>
                </div>
                <span
                  className="text-xs font-bold px-2 py-0.5 rounded-full"
                  style={{ background: '#DCFCE7', color: '#059669', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                >
                  {k.change}
                </span>
              </div>
              <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{k.value}</p>
              <p className="text-xs text-slate-500 mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{k.label}</p>
            </div>
          ))}
        </div>
      ) : null}

      {/* ── Charts Row ── */}
      <div className="grid grid-cols-2 gap-5 mb-5">
        {/* Revenue Chart */}
        {loading ? (
          <ChartSkeleton title="الإيرادات الشهرية" subtitle="آخر 6 أشهر" iconBg="#DCFCE7" iconColor="#059669" icon="ri-line-chart-fill" />
        ) : report ? (
          <div className="bg-white rounded-2xl p-5" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الإيرادات الشهرية</h3>
                <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {report.window.from} — {report.window.to}
                </p>
              </div>
              <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#DCFCE7' }}>
                <i className="ri-line-chart-fill text-base" style={{ color: '#059669' }}></i>
              </div>
            </div>
            <ResponsiveContainer width="100%" height={200}>
              <AreaChart data={revenueChartData}>
                <defs>
                  <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#1E3A8A" stopOpacity={0.15} />
                    <stop offset="95%" stopColor="#1E3A8A" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#F1F5F9" />
                <XAxis dataKey="month" tick={{ fontSize: 10, fontFamily: '"IBM Plex Sans Arabic", sans-serif', fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 10, fontFamily: '"IBM Plex Sans Arabic", sans-serif', fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                <Tooltip
                  contentStyle={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', fontSize: '12px', borderRadius: '12px', border: '1px solid #E2E8F0' }}
                  formatter={(value) => [`${Number(value).toLocaleString()} ر`, 'الإيرادات']}
                />
                <Area type="monotone" dataKey="revenue" stroke="#1E3A8A" strokeWidth={2.5} fill="url(#revGrad)" />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        ) : null}

        {/* Trips Chart */}
        {loading ? (
          <ChartSkeleton title="الرحلات الأسبوعية" subtitle="هذا الأسبوع" iconBg="#EEF2FF" iconColor="#1E3A8A" icon="ri-bar-chart-2-fill" />
        ) : report ? (
          <div className="bg-white rounded-2xl p-5" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>الرحلات الأسبوعية</h3>
                <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>هذا الأسبوع</p>
              </div>
              <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#EEF2FF' }}>
                <i className="ri-bar-chart-2-fill text-base" style={{ color: '#1E3A8A' }}></i>
              </div>
            </div>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={tripsChartData} barSize={14}>
                <CartesianGrid strokeDasharray="3 3" stroke="#F1F5F9" />
                <XAxis dataKey="day" tick={{ fontSize: 10, fontFamily: '"IBM Plex Sans Arabic", sans-serif', fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 10, fontFamily: '"IBM Plex Sans Arabic", sans-serif', fill: '#94a3b8' }} axisLine={false} tickLine={false} />
                <Tooltip contentStyle={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif', fontSize: '12px', borderRadius: '12px', border: '1px solid #E2E8F0' }} />
                <Bar dataKey="completed" fill="#1E3A8A" radius={[4, 4, 0, 0]} name="مكتملة" />
                <Bar dataKey="cancelled" fill="#FCA5A5" radius={[4, 4, 0, 0]} name="ملغاة" />
              </BarChart>
            </ResponsiveContainer>
          </div>
        ) : null}
      </div>

      {/* ── Top Captains Table ── */}
      {loading ? (
        <TableSkeleton />
      ) : report ? (
        <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
          <div className="flex items-center gap-2 px-6 py-4 border-b" style={{ borderColor: '#F1F5F9' }}>
            <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{ background: '#FEF3C7' }}>
              <i className="ri-medal-fill text-base" style={{ color: '#D97706' }}></i>
            </div>
            <h3 className="font-bold text-slate-800 text-sm" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>أفضل السائقين أداءً</h3>
          </div>
          <table className="w-full">
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['الترتيب', 'السائق', 'عدد الرحلات', 'التقييم', 'الإيرادات'].map((h) => (
                  <th
                    key={h}
                    className="text-right px-6 py-3 text-xs font-bold text-slate-500 whitespace-nowrap"
                    style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {report.top_captains.map((d, i) => (
                <tr key={d.id} className="border-t hover:bg-slate-50 transition-colors" style={{ borderColor: '#F8FAFC' }}>
                  <td className="px-6 py-3.5">
                    <div
                      className="w-7 h-7 rounded-xl flex items-center justify-center font-black text-sm"
                      style={{
                        background: i === 0 ? '#FEF3C7' : i === 1 ? '#F1F5F9' : i === 2 ? '#FEE2E2' : '#F8FAFC',
                        color: i === 0 ? '#D97706' : i === 1 ? '#64748b' : i === 2 ? '#EF4444' : '#94a3b8',
                        fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                      }}
                    >
                      {d.rank}
                    </div>
                  </td>
                  <td className="px-6 py-3.5">
                    <div className="flex items-center gap-3">
                      <div className="w-9 h-9 rounded-xl overflow-hidden flex-shrink-0">
                        <img
                          src={d.image}
                          alt={d.name}
                          className="w-full h-full object-cover object-top"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src =
                              `https://ui-avatars.com/api/?name=${encodeURIComponent(d.name)}&background=EEF2FF&color=1E3A8A&size=80`;
                          }}
                        />
                      </div>
                      <span className="text-sm font-bold text-slate-800 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {d.name}
                      </span>
                    </div>
                  </td>
                  <td className="px-6 py-3.5">
                    <span className="text-sm font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {d.trips_count} رحلة
                    </span>
                  </td>
                  <td className="px-6 py-3.5">
                    <div className="flex items-center gap-1.5">
                      <i className="ri-star-fill text-sm" style={{ color: '#F59E0B' }}></i>
                      <span className="text-sm font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {d.rating}
                      </span>
                    </div>
                  </td>
                  <td className="px-6 py-3.5">
                    <span className="text-sm font-bold" style={{ color: '#059669', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                      {d.revenue.toLocaleString('ar-SA')} {d.currency}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}

    </DashboardShell>
  );
}