"use client";

import { useState, useEffect, useCallback } from "react";
import {
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

interface ReportData {
  totalAmount: number;
  expenseCount: number;
  monthlyAverage: number;
  topCategory: { name: string; nameAr: string | null; total: number } | null;
  categoryBreakdown: {
    name: string;
    nameAr: string | null;
    color: string;
    total: number;
    count: number;
  }[];
  monthlyTrend: { month: string; total: number }[];
  topVendors: { vendor: string; total: number }[];
}

const t = {
  en: {
    title: "Expense Report",
    totalExpenses: "Total Expenses",
    monthlyAvg: "Monthly Average",
    topCategory: "Top Category",
    expenseCount: "Transactions",
    byCategory: "By Category",
    monthlyTrend: "Monthly Trend",
    topVendors: "Top Vendors",
    dateFrom: "From",
    dateTo: "To",
    applyFilter: "Apply",
    noData: "No expense data for the selected period.",
    amount: "Amount",
    month: "Month",
    vendor: "Vendor",
  },
  ar: {
    title: "تقرير المصروفات",
    totalExpenses: "إجمالي المصروفات",
    monthlyAvg: "المتوسط الشهري",
    topCategory: "أعلى فئة",
    expenseCount: "المعاملات",
    byCategory: "حسب الفئة",
    monthlyTrend: "الاتجاه الشهري",
    topVendors: "أعلى الموردين",
    dateFrom: "من",
    dateTo: "إلى",
    applyFilter: "تطبيق",
    noData: "لا توجد بيانات مصروفات للفترة المحددة.",
    amount: "المبلغ",
    month: "الشهر",
    vendor: "المورد",
  },
};

interface ExpenseReportProps {
  lang: string;
}

export default function ExpenseReport({ lang }: ExpenseReportProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  const [report, setReport] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");

  const fetchReport = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (dateFrom) params.set("dateFrom", dateFrom);
      if (dateTo) params.set("dateTo", dateTo);

      const res = await fetch(`/api/dashboard/expenses/report?${params}`);
      const data = await res.json();
      if (data.success) setReport(data.report);
    } catch {
      /* ignore */
    }
    setLoading(false);
  }, [dateFrom, dateTo]);

  useEffect(() => {
    fetchReport();
  }, [fetchReport]);

  const formatCurrency = (val: number) =>
    val.toLocaleString(isAr ? "ar-QA" : "en-QA", {
      style: "currency",
      currency: "QAR",
    });

  if (loading) {
    return (
      <div className="flex h-60 items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-indigo-300 border-t-indigo-600" />
      </div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"}>
      {/* Date range filter */}
      <div className="mb-6 flex flex-wrap items-end gap-3">
        <div>
          <label className="mb-1 block text-xs text-gray-500">
            {labels.dateFrom}
          </label>
          <input
            type="date"
            value={dateFrom}
            onChange={(e) => setDateFrom(e.target.value)}
            className="rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
          />
        </div>
        <div>
          <label className="mb-1 block text-xs text-gray-500">
            {labels.dateTo}
          </label>
          <input
            type="date"
            value={dateTo}
            onChange={(e) => setDateTo(e.target.value)}
            className="rounded-lg border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
          />
        </div>
        <button
          onClick={fetchReport}
          className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"
        >
          {labels.applyFilter}
        </button>
      </div>

      {!report || report.expenseCount === 0 ? (
        <div className="rounded-lg border border-dashed border-gray-300 p-8 text-center text-gray-500 dark:border-gray-600">
          {labels.noData}
        </div>
      ) : (
        <>
          {/* Summary cards */}
          <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
            <SummaryCard
              label={labels.totalExpenses}
              value={formatCurrency(report.totalAmount)}
              color="bg-red-50 dark:bg-red-900/20"
            />
            <SummaryCard
              label={labels.monthlyAvg}
              value={formatCurrency(report.monthlyAverage)}
              color="bg-blue-50 dark:bg-blue-900/20"
            />
            <SummaryCard
              label={labels.topCategory}
              value={
                report.topCategory
                  ? isAr && report.topCategory.nameAr
                    ? report.topCategory.nameAr
                    : report.topCategory.name
                  : "—"
              }
              color="bg-purple-50 dark:bg-purple-900/20"
            />
            <SummaryCard
              label={labels.expenseCount}
              value={String(report.expenseCount)}
              color="bg-green-50 dark:bg-green-900/20"
            />
          </div>

          {/* Charts */}
          <div className="mb-6 grid gap-6 lg:grid-cols-2">
            {/* Pie chart by category */}
            <div className="rounded-xl border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
              <h4 className="mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">
                {labels.byCategory}
              </h4>
              <ResponsiveContainer width="100%" height={280}>
                <PieChart>
                  <Pie
                    data={report.categoryBreakdown}
                    dataKey="total"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    outerRadius={100}
                    label={({
                      name,
                      percent,
                    }: {
                      name?: string;
                      percent?: number;
                    }) => `${name ?? ""} ${((percent ?? 0) * 100).toFixed(0)}%`}
                  >
                    {report.categoryBreakdown.map((entry, i) => (
                      <Cell key={i} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value: unknown) =>
                      formatCurrency(Number(value))
                    }
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>

            {/* Bar chart monthly trend */}
            <div className="rounded-xl border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
              <h4 className="mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">
                {labels.monthlyTrend}
              </h4>
              <ResponsiveContainer width="100%" height={280}>
                <BarChart data={report.monthlyTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} />
                  <Tooltip
                    formatter={(value: unknown) =>
                      formatCurrency(Number(value))
                    }
                  />
                  <Legend />
                  <Bar
                    dataKey="total"
                    name={labels.amount}
                    fill="#6366f1"
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Top vendors */}
          {report.topVendors.length > 0 && (
            <div className="rounded-xl border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
              <h4 className="mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">
                {labels.topVendors}
              </h4>
              <div className="space-y-2">
                {report.topVendors.map((v) => (
                  <div
                    key={v.vendor}
                    className="flex items-center justify-between text-sm"
                  >
                    <span className="text-gray-700 dark:text-gray-300">
                      {v.vendor}
                    </span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {formatCurrency(v.total)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function SummaryCard({
  label,
  value,
  color,
}: {
  label: string;
  value: string;
  color: string;
}) {
  return (
    <div className={`rounded-xl p-4 ${color}`}>
      <p className="text-xs text-gray-500 dark:text-gray-400">{label}</p>
      <p className="mt-1 text-lg font-bold text-gray-900 dark:text-white">
        {value}
      </p>
    </div>
  );
}
