import { useState, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Wallet, TrendingUp, TrendingDown } from "lucide-react";
import { useDashboard } from "../hooks/useDashboard";
import { PageHelp } from "../components/shared/PageHelp";
import PeriodSelector from "../components/dashboard/PeriodSelector";
import CategoryPieChart from "../components/dashboard/CategoryPieChart";
import CategoriesV1DiscoveryBanner from "../components/dashboard/CategoriesV1DiscoveryBanner";
import CategoryOverTimeChart from "../components/reports/CategoryOverTimeChart";
import BudgetVsActualTable from "../components/reports/BudgetVsActualTable";
import TransactionDetailModal from "../components/shared/TransactionDetailModal";
import type { CategoryBreakdownItem } from "../shared/types";
import { computeDateRange, buildMonthOptions } from "../utils/dateRange";

const fmt = new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" });

export default function DashboardPage() {
  const { t, i18n } = useTranslation();
  const { state, setPeriod, setCustomDates, setBudgetMonth } = useDashboard();
  const { summary, categoryBreakdown, categoryOverTime, budgetVsActual, period, isLoading } = state;

  const [hiddenCategories, setHiddenCategories] = useState<Set<string>>(new Set());
  const [detailModal, setDetailModal] = useState<CategoryBreakdownItem | null>(null);

  const toggleHidden = useCallback((name: string) => {
    setHiddenCategories((prev) => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name);
      else next.add(name);
      return next;
    });
  }, []);

  const showAll = useCallback(() => setHiddenCategories(new Set()), []);

  const viewDetails = useCallback((item: CategoryBreakdownItem) => {
    setDetailModal(item);
  }, []);

  const balance = summary.totalAmount;
  const balanceColor =
    balance > 0
      ? "text-[var(--positive)]"
      : balance < 0
        ? "text-[var(--negative)]"
        : "text-[var(--primary)]";

  const cards = [
    {
      labelKey: "dashboard.balance",
      value: fmt.format(balance),
      icon: Wallet,
      color: balanceColor,
    },
    {
      labelKey: "dashboard.income",
      value: fmt.format(summary.incomeTotal),
      icon: TrendingUp,
      color: "text-[var(--positive)]",
    },
    {
      labelKey: "dashboard.expenses",
      value: fmt.format(Math.abs(summary.expenseTotal)),
      icon: TrendingDown,
      color: "text-[var(--negative)]",
    },
  ];

  const monthOptions = useMemo(() => buildMonthOptions(i18n.language), [i18n.language]);

  const { dateFrom, dateTo } = computeDateRange(period, state.customDateFrom, state.customDateTo);

  return (
    <div className={isLoading ? "opacity-50 pointer-events-none" : ""}>
      <CategoriesV1DiscoveryBanner />
      <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <h1 className="text-2xl font-bold">{t("dashboard.title")}</h1>
          <PageHelp helpKey="dashboard" />
        </div>
        <PeriodSelector
          value={period}
          onChange={setPeriod}
          customDateFrom={state.customDateFrom}
          customDateTo={state.customDateTo}
          onCustomDateChange={setCustomDates}
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {cards.map((card) => (
          <div
            key={card.labelKey}
            className="bg-[var(--card)] rounded-xl p-5 border border-[var(--border)] shadow-sm"
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm text-[var(--muted-foreground)]">
                {t(card.labelKey)}
              </span>
              <card.icon size={20} className={card.color} />
            </div>
            <p className="text-2xl font-semibold">{card.value}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-6">
        <div className="lg:col-span-1">
          <h2 className="text-lg font-semibold mb-3">{t("dashboard.expensesByCategory")}</h2>
          <CategoryPieChart
            data={categoryBreakdown}
            hiddenCategories={hiddenCategories}
            onToggleHidden={toggleHidden}
            onShowAll={showAll}
            onViewDetails={viewDetails}
          />
        </div>
        <div className="lg:col-span-3">
          <h2 className="text-lg font-semibold mb-3 flex items-center gap-2 flex-wrap">
            {t("reports.bva.titlePrefix")}
            <select
              value={`${state.budgetYear}-${state.budgetMonth}`}
              onChange={(e) => {
                const [y, m] = e.target.value.split("-").map(Number);
                setBudgetMonth(y, m);
              }}
              className="text-base font-semibold bg-[var(--card)] border border-[var(--border)] rounded-lg px-2 py-0.5 cursor-pointer hover:bg-[var(--muted)] transition-colors"
            >
              {monthOptions.map((opt) => (
                <option key={opt.key} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </h2>
          <BudgetVsActualTable data={budgetVsActual} />
        </div>
      </div>

      <div className="mb-6">
        <h2 className="text-lg font-semibold mb-3">{t("dashboard.expensesOverTime")}</h2>
        <CategoryOverTimeChart
          data={categoryOverTime}
          hiddenCategories={hiddenCategories}
          onToggleHidden={toggleHidden}
          onShowAll={showAll}
          onViewDetails={viewDetails}
        />
      </div>

      {detailModal && (
        <TransactionDetailModal
          categoryId={detailModal.category_id}
          categoryName={detailModal.category_name}
          categoryColor={detailModal.category_color}
          dateFrom={dateFrom}
          dateTo={dateTo}
          onClose={() => setDetailModal(null)}
        />
      )}
    </div>
  );
}
