'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  Plus,
  Calendar,
  ArrowUpRight,
  ArrowDownRight,
  Package,
  Receipt,
  FileText,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import StatCard from '@/components/StatCard';
import Modal from '@/components/Modal';
import LoadingSpinner from '@/components/LoadingSpinner';
import { formatCurrency, formatDate, formatDateShort, cn } from '@/lib/utils';
import { orderApi, expenseApi, bookkeepingApi } from '@/lib/api';
import type { Order, Expense } from '@/types';
import { useAuth } from '@/components/AuthContext';
import { canAccessFinancePages } from '@/lib/roles';
import { useRouter } from 'next/navigation';

const EXPENSE_CATEGORIES = [
  { value: 'ingredient', label: 'Bahan Baku' },
  { value: 'salary', label: 'Gaji' },
  { value: 'rent', label: 'Sewa' },
  { value: 'utility', label: 'Utilitas' },
  { value: 'equipment', label: 'Peralatan' },
  { value: 'other', label: 'Lainnya' },
];

const ITEMS_PER_PAGE = 10;

export default function PembukuanPage() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (authLoading) return;
    if (!canAccessFinancePages(user)) {
      router.replace('/');
    }
  }, [user, authLoading, router]);

  // Summary stats (from server aggregate)
  const [totalIncome, setTotalIncome] = useState(0);
  const [totalExpenses, setTotalExpenses] = useState(0);
  const [netProfit, setNetProfit] = useState(0);

  // Income tab (server-paginated)
  const [incomeOrders, setIncomeOrders] = useState<Order[]>([]);
  const [incomePage, setIncomePage] = useState(1);
  const [incomeTotalPages, setIncomeTotalPages] = useState(1);
  const [incomeTotalItems, setIncomeTotalItems] = useState(0);
  const [incomeFetching, setIncomeFetching] = useState(false);

  // Expense tab (server-paginated)
  const [expenses, setExpenses] = useState<Expense[]>([]);
  const [expensePage, setExpensePage] = useState(1);
  const [expenseTotalPages, setExpenseTotalPages] = useState(1);
  const [expenseTotalItems, setExpenseTotalItems] = useState(0);
  const [expenseFetching, setExpenseFetching] = useState(false);

  const [loading, setLoading] = useState(true);
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [showExpenseModal, setShowExpenseModal] = useState(false);
  const [activeTab, setActiveTab] = useState<'income' | 'expense'>('income');

  // Expense form state
  const [expenseForm, setExpenseForm] = useState({
    category: 'ingredient',
    description: '',
    amount: '',
    date: new Date().toISOString().slice(0, 10),
    notes: '',
  });

  // Fetch summary stats from server
  const fetchSummary = useCallback(async (from: string, to: string) => {
    if (!canAccessFinancePages(user)) return;
    try {
      const params: Record<string, string> = {};
      if (from) params.date_from = from;
      if (to) params.date_to = to;
      const summary = await bookkeepingApi.getSummary(params);
      setTotalIncome(Number(summary.total_income));
      setTotalExpenses(Number(summary.total_expenses));
      setNetProfit(Number(summary.net_profit));
    } catch (error) {
      console.error('Failed to load summary:', error);
    }
  }, [user]);

  // Fetch income orders (server-paginated)
  const fetchIncome = useCallback(async (pg: number, from: string, to: string) => {
    setIncomeFetching(true);
    try {
      const params: Record<string, string | number> = {
        status: 'completed',
        payment_status: 'paid',
        page: pg,
        per_page: ITEMS_PER_PAGE,
      };
      if (from) params.date_from = from;
      if (to) params.date_to = to;
      const result = await orderApi.getAll(params);
      setIncomeOrders(
        result.data
          .map((o) => ({
            ...o,
            subtotal: Number(o.subtotal),
            tax: Number(o.tax),
            discount: Number(o.discount),
            total: Number(o.total),
          }))
      );
      setIncomeTotalItems(result.total);
      setIncomeTotalPages(result.last_page);
    } catch (error) {
      console.error('Failed to load income orders:', error);
    } finally {
      setIncomeFetching(false);
    }
  }, []);

  // Fetch expenses (server-paginated)
  const fetchExpenses = useCallback(async (pg: number, from: string, to: string) => {
    setExpenseFetching(true);
    try {
      const params: Record<string, string | number> = {
        page: pg,
        per_page: ITEMS_PER_PAGE,
      };
      if (from) params.date_from = from;
      if (to) params.date_to = to;
      const result = await expenseApi.getAll(params);
      setExpenses(
        result.data.map((e) => ({
          ...e,
          amount: Number(e.amount),
          date: String(e.date).slice(0, 10),
        }))
      );
      setExpenseTotalItems(result.total ?? 0);
      setExpenseTotalPages(result.last_page ?? 1);
    } catch (error) {
      console.error('Failed to load expenses:', error);
    } finally {
      setExpenseFetching(false);
    }
  }, []);

  // Initial load (wait for auth + finance role)
  useEffect(() => {
    if (authLoading) return;
    if (!canAccessFinancePages(user)) {
      setLoading(false);
      return;
    }
    const init = async () => {
      await Promise.all([
        fetchSummary('', ''),
        fetchIncome(1, '', ''),
        fetchExpenses(1, '', ''),
      ]);
      setLoading(false);
    };
    init();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authLoading, user]);

  // Re-fetch all when date filters change
  useEffect(() => {
    if (loading) return;
    setIncomePage(1);
    setExpensePage(1);
    fetchSummary(dateFrom, dateTo);
    fetchIncome(1, dateFrom, dateTo);
    fetchExpenses(1, dateFrom, dateTo);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateFrom, dateTo]);

  // Re-fetch income when page changes
  useEffect(() => {
    if (loading) return;
    fetchIncome(incomePage, dateFrom, dateTo);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [incomePage]);

  // Re-fetch expenses when page changes
  useEffect(() => {
    if (loading) return;
    fetchExpenses(expensePage, dateFrom, dateTo);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [expensePage]);

  // Bar chart data (simple CSS-based)
  const maxBarValue = Math.max(totalIncome, totalExpenses, 1);
  const incomePercent = Math.round((totalIncome / maxBarValue) * 100);
  const expensePercent = Math.round((totalExpenses / maxBarValue) * 100);
  const netProfitPercent = Math.round((Math.abs(netProfit) / maxBarValue) * 100);

  const [expenseSubmitting, setExpenseSubmitting] = useState(false);

  const handleAddExpense = async () => {
    if (!expenseForm.description || !expenseForm.amount || expenseSubmitting) return;
    setExpenseSubmitting(true);
    try {
      await expenseApi.create({
        category: expenseForm.category,
        description: expenseForm.description,
        amount: Number(expenseForm.amount),
        date: expenseForm.date,
        notes: expenseForm.notes || undefined,
      });
      // Re-fetch expenses and summary to reflect new data
      await Promise.all([
        fetchExpenses(1, dateFrom, dateTo),
        fetchSummary(dateFrom, dateTo),
      ]);
      setExpensePage(1);
      setExpenseForm({
        category: 'ingredient',
        description: '',
        amount: '',
        date: new Date().toISOString().slice(0, 10),
        notes: '',
      });
      setShowExpenseModal(false);
    } catch (error) {
      console.error('Failed to create expense:', error);
      alert('Gagal menyimpan pengeluaran. Silakan coba lagi.');
    } finally {
      setExpenseSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center py-32">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  return (
    <div className="p-4 lg:p-8 space-y-6 lg:space-y-8 animate-fade-in">
      {/* ── Page Header ── */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="space-y-2">
          <h1 className="text-2xl lg:text-3xl font-bold text-blue-900 tracking-tight">
            Pembukuan
          </h1>
          <div className="flex items-center gap-2 sm:gap-3 flex-wrap">
            <p className="text-sm lg:text-base text-blue-600/80">
              Laporan keuangan dan pengeluaran
            </p>
            {/* Net profit indicator */}
            <div
              className={cn(
                'inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold shadow-sm',
                netProfit >= 0
                  ? 'bg-emerald-50 text-emerald-700 border border-emerald-200'
                  : 'bg-red-50 text-red-600 border border-red-200'
              )}
            >
              {netProfit >= 0 ? (
                <ArrowUpRight className="h-3.5 w-3.5" />
              ) : (
                <ArrowDownRight className="h-3.5 w-3.5" />
              )}
              <span>
                {netProfit >= 0 ? 'Untung' : 'Rugi'}{' '}
                {formatCurrency(Math.abs(netProfit))}
              </span>
            </div>
          </div>
        </div>
        <button
          onClick={() => setShowExpenseModal(true)}
          className="inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-blue-600 to-blue-500 px-6 py-3 text-sm font-semibold text-white hover:from-blue-700 hover:to-blue-600 transition-all duration-200 cursor-pointer active:scale-[0.98] shadow-lg shadow-blue-500/30"
        >
          <Plus className="h-4 w-4" />
          Tambah Pengeluaran
        </button>
      </div>

      {/* ── Date Filter ── */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-5 lg:px-6 lg:py-5 border border-blue-100 shadow-sm">
        <div className="flex items-center gap-3 flex-wrap">
          <div className="flex items-center gap-2 text-blue-700">
            <Calendar className="h-4 w-4" />
            <span className="text-sm font-semibold">Filter Tanggal</span>
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <input
              type="date"
              value={dateFrom}
              onChange={(e) => setDateFrom(e.target.value)}
              className="rounded-xl border border-blue-200 bg-white px-4 py-2.5 text-sm text-blue-900 focus:border-blue-400 focus:ring-2 focus:ring-blue-200/50 outline-none transition-all min-h-[44px]"
            />
            <span className="text-blue-400 text-sm font-medium">sampai</span>
            <input
              type="date"
              value={dateTo}
              onChange={(e) => setDateTo(e.target.value)}
              className="rounded-xl border border-blue-200 bg-white px-4 py-2.5 text-sm text-blue-900 focus:border-blue-400 focus:ring-2 focus:ring-blue-200/50 outline-none transition-all min-h-[44px]"
            />
            {(dateFrom || dateTo) && (
              <button
                onClick={() => {
                  setDateFrom('');
                  setDateTo('');
                }}
                className="rounded-lg px-3 py-2 text-xs font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-colors cursor-pointer"
              >
                Reset
              </button>
            )}
          </div>
        </div>
      </div>

      {/* ── Summary Cards ── */}
      <div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 animate-slide-up">
        <StatCard
          title="Total Pemasukan"
          value={totalIncome}
          icon={TrendingUp}
          isCurrency
          accentColor="green"
        />
        <StatCard
          title="Total Pengeluaran"
          value={totalExpenses}
          icon={TrendingDown}
          isCurrency
          accentColor="purple"
        />
        <StatCard
          title="Laba Bersih"
          value={netProfit}
          icon={DollarSign}
          isCurrency
          accentColor="amber"
        />
      </div>

      {/* ── Visual Bar Chart ── */}
      <div className="rounded-2xl border border-blue-100 bg-white p-6 lg:p-8 shadow-sm">
        <h2 className="text-lg lg:text-xl font-bold text-blue-900 mb-6 lg:mb-8">
          Perbandingan Pemasukan vs Pengeluaran
        </h2>
        <div className="space-y-6">
          {/* Income Bar */}
          <div className="space-y-3">
            <div className="flex items-center justify-between text-sm">
              <span className="font-semibold text-blue-700">Pemasukan</span>
              <span className="font-bold text-emerald-700 tabular-nums">
                {formatCurrency(totalIncome)}
              </span>
            </div>
            <div className="relative h-12 w-full rounded-xl bg-emerald-50 overflow-hidden border border-emerald-100">
              <div
                className="h-full rounded-xl bg-gradient-to-r from-emerald-500 to-emerald-400 transition-all duration-700 ease-out flex items-center justify-end shadow-sm"
                style={{
                  width: `${Math.max((totalIncome / maxBarValue) * 100, totalIncome > 0 ? 8 : 0)}%`,
                }}
              >
                {totalIncome > 0 && (
                  <span className="text-xs font-bold text-white pr-4 drop-shadow-sm tabular-nums">
                    {incomePercent}%
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Expense Bar */}
          <div className="space-y-3">
            <div className="flex items-center justify-between text-sm">
              <span className="font-semibold text-blue-700">Pengeluaran</span>
              <span className="font-bold text-red-600 tabular-nums">
                {formatCurrency(totalExpenses)}
              </span>
            </div>
            <div className="relative h-12 w-full rounded-xl bg-red-50 overflow-hidden border border-red-100">
              <div
                className="h-full rounded-xl bg-gradient-to-r from-red-500 to-red-400 transition-all duration-700 ease-out flex items-center justify-end shadow-sm"
                style={{
                  width: `${Math.max((totalExpenses / maxBarValue) * 100, totalExpenses > 0 ? 8 : 0)}%`,
                }}
              >
                {totalExpenses > 0 && (
                  <span className="text-[11px] font-bold text-white pr-3 drop-shadow-sm tabular-nums">
                    {expensePercent}%
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Net Profit Bar */}
          <div className="space-y-2">
            <div className="flex items-center justify-between text-sm">
              <span className="font-medium text-brand-600">Laba Bersih</span>
              <span
                className={cn(
                  'font-bold tabular-nums',
                  netProfit >= 0 ? 'text-amber-700' : 'text-red-600'
                )}
              >
                {formatCurrency(Math.abs(netProfit))}
                {netProfit < 0 && ' (Rugi)'}
              </span>
            </div>
            <div className="relative h-10 w-full rounded-full bg-amber-50 overflow-hidden">
              <div
                className={cn(
                  'h-full rounded-full transition-all duration-700 ease-out flex items-center justify-end',
                  netProfit >= 0
                    ? 'bg-gradient-to-r from-amber-500 via-amber-400 to-amber-300'
                    : 'bg-gradient-to-r from-red-400 via-red-300 to-red-200'
                )}
                style={{
                  width: `${Math.max((Math.abs(netProfit) / maxBarValue) * 100, Math.abs(netProfit) > 0 ? 8 : 0)}%`,
                }}
              >
                {Math.abs(netProfit) > 0 && (
                  <span className="text-[11px] font-bold text-white pr-3 drop-shadow-sm tabular-nums">
                    {netProfitPercent}%
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Tab Switcher (pill-style) ── */}
      <div className="relative flex gap-1 rounded-2xl bg-brand-100/60 p-1.5 w-fit max-w-full overflow-x-auto scrollbar-hide">
        <button
          onClick={() => setActiveTab('income')}
          className={cn(
            'relative z-10 rounded-xl px-6 py-2.5 text-sm font-semibold transition-all duration-200 cursor-pointer min-h-[44px]',
            activeTab === 'income'
              ? 'bg-white text-brand-700 shadow-md'
              : 'text-brand-500 hover:text-brand-700'
          )}
        >
          <span className="flex items-center gap-2">
            <TrendingUp className="h-4 w-4" />
            Pemasukan
          </span>
        </button>
        <button
          onClick={() => setActiveTab('expense')}
          className={cn(
            'relative z-10 rounded-xl px-6 py-2.5 text-sm font-semibold transition-all duration-200 cursor-pointer min-h-[44px]',
            activeTab === 'expense'
              ? 'bg-white text-brand-700 shadow-md'
              : 'text-brand-500 hover:text-brand-700'
          )}
        >
          <span className="flex items-center gap-2">
            <TrendingDown className="h-4 w-4" />
            Pengeluaran
          </span>
        </button>
      </div>

      {/* ── Income Table ── */}
      {activeTab === 'income' && (
        <div
          className={cn(
            'rounded-2xl border border-border bg-white overflow-hidden animate-fade-in transition-opacity duration-200',
            incomeFetching && 'opacity-60 pointer-events-none'
          )}
          style={{ boxShadow: 'var(--shadow-card)' }}
        >
          <div className="border-b border-brand-100 px-5 lg:px-6 py-4">
            <div className="flex items-center gap-2.5">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-50">
                <Receipt className="h-4 w-4 text-emerald-600" />
              </div>
              <h2 className="text-sm lg:text-base font-semibold text-brand-700 font-heading">
                Pemasukan dari Pesanan
              </h2>
              {incomeTotalItems > 0 && (
                <span className="ml-auto text-xs font-medium text-brand-400 tabular-nums">
                  {incomeTotalItems} transaksi
                </span>
              )}
            </div>
          </div>

          {/* Mobile: Card view with green left border */}
          <div className="divide-y divide-brand-50 lg:hidden">
            {incomeOrders.map((order) => (
              <div
                key={order.id}
                className="relative p-4 pl-5 space-y-1.5 hover:bg-brand-50/30 transition-colors"
              >
                {/* Green left border accent */}
                <div className="absolute left-0 top-3 bottom-3 w-1 rounded-r-full bg-emerald-400" />
                <div className="flex items-center justify-between">
                  <span className="text-sm font-semibold text-brand-700">
                    {order.order_number}
                  </span>
                  <span className="text-sm font-bold text-emerald-700 tabular-nums">
                    +{formatCurrency(order.total)}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs text-brand-500">
                    {order.customer_name || '-'}
                  </span>
                  <span className="inline-flex items-center rounded-full bg-brand-50 px-2 py-0.5 text-[11px] font-medium text-brand-500 capitalize">
                    {order.payment_method}
                  </span>
                </div>
                <p className="text-xs text-brand-400">
                  {formatDate(order.created_at)}
                </p>
              </div>
            ))}
            {incomeOrders.length === 0 && !incomeFetching && (
              <EmptyState type="income" />
            )}
            {incomeTotalItems > 0 && (
              <div className="p-4 bg-gradient-to-r from-emerald-50 via-emerald-50/80 to-amber-50/40 flex items-center justify-between">
                <span className="text-sm font-semibold text-brand-700">
                  Total Pemasukan
                </span>
                <span className="text-base font-bold text-emerald-700 tabular-nums">
                  {formatCurrency(totalIncome)}
                </span>
              </div>
            )}
          </div>

          {/* Desktop: Table view */}
          <div className="hidden lg:block overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-brand-100 bg-brand-50/40">
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Tanggal
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    No. Pesanan
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Pelanggan
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Pembayaran
                  </th>
                  <th className="px-6 py-3.5 text-right text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Jumlah
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-brand-50">
                {incomeOrders.map((order) => (
                  <tr
                    key={order.id}
                    className="hover:bg-emerald-50/20 transition-colors"
                  >
                    <td className="px-6 py-3.5 text-brand-500">
                      {formatDate(order.created_at)}
                    </td>
                    <td className="px-6 py-3.5 font-medium text-brand-700">
                      {order.order_number}
                    </td>
                    <td className="px-6 py-3.5 text-brand-600">
                      {order.customer_name || '-'}
                    </td>
                    <td className="px-6 py-3.5">
                      <span className="inline-flex items-center rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-600 capitalize">
                        {order.payment_method}
                      </span>
                    </td>
                    <td className="px-6 py-3.5 text-right font-semibold text-emerald-700 tabular-nums">
                      +{formatCurrency(order.total)}
                    </td>
                  </tr>
                ))}
                {incomeOrders.length === 0 && !incomeFetching && (
                  <tr>
                    <td colSpan={5}>
                      <EmptyState type="income" />
                    </td>
                  </tr>
                )}
              </tbody>
              {incomeTotalItems > 0 && (
                <tfoot>
                  <tr className="border-t-2 border-emerald-100">
                    <td
                      colSpan={5}
                      className="px-0 py-0"
                    >
                      <div className="bg-gradient-to-r from-emerald-50 via-emerald-50/80 to-amber-50/40 px-6 py-4 flex items-center justify-between">
                        <span className="font-semibold text-brand-700">
                          Total Pemasukan
                        </span>
                        <span className="text-lg font-bold text-emerald-700 tabular-nums">
                          {formatCurrency(totalIncome)}
                        </span>
                      </div>
                    </td>
                  </tr>
                </tfoot>
              )}
            </table>
          </div>

          {/* Income Pagination */}
          {incomeTotalPages > 1 && (
            <PaginationBar
              page={incomePage}
              totalPages={incomeTotalPages}
              totalItems={incomeTotalItems}
              perPage={ITEMS_PER_PAGE}
              fetching={incomeFetching}
              onPageChange={setIncomePage}
            />
          )}
        </div>
      )}

      {/* ── Expense Table ── */}
      {activeTab === 'expense' && (
        <div
          className={cn(
            'rounded-2xl border border-border bg-white overflow-hidden animate-fade-in transition-opacity duration-200',
            expenseFetching && 'opacity-60 pointer-events-none'
          )}
          style={{ boxShadow: 'var(--shadow-card)' }}
        >
          <div className="border-b border-brand-100 px-5 lg:px-6 py-4 flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-violet-50">
                <FileText className="h-4 w-4 text-violet-600" />
              </div>
              <h2 className="text-sm lg:text-base font-semibold text-brand-700 font-heading">
                Daftar Pengeluaran
              </h2>
            </div>
            {expenseTotalItems > 0 && (
              <span className="text-xs font-medium text-brand-400 tabular-nums">
                {expenseTotalItems} transaksi
              </span>
            )}
          </div>

          {/* Mobile: Card view with red left border */}
          <div className="divide-y divide-brand-50 lg:hidden">
            {expenses.map((expense) => (
              <div
                key={expense.id}
                className="relative p-4 pl-5 space-y-1.5 hover:bg-brand-50/30 transition-colors"
              >
                {/* Red left border accent */}
                <div className="absolute left-0 top-3 bottom-3 w-1 rounded-r-full bg-red-400" />
                <div className="flex items-center justify-between">
                  <span className="text-sm font-semibold text-brand-700 truncate mr-2">
                    {expense.description}
                  </span>
                  <span className="text-sm font-bold text-red-600 tabular-nums shrink-0">
                    -{formatCurrency(expense.amount)}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="inline-flex rounded-full bg-violet-50 px-2.5 py-0.5 text-[11px] font-medium text-violet-700 border border-violet-100">
                    {EXPENSE_CATEGORIES.find((c) => c.value === expense.category)
                      ?.label ?? expense.category}
                  </span>
                  <span className="text-xs text-brand-400">
                    {formatDateShort(expense.date)}
                  </span>
                </div>
                {expense.notes && (
                  <p className="text-xs text-brand-400 truncate italic">
                    {expense.notes}
                  </p>
                )}
              </div>
            ))}
            {expenses.length === 0 && !expenseFetching && (
              <EmptyState type="expense" />
            )}
            {expenseTotalItems > 0 && (
              <div className="p-4 bg-gradient-to-r from-red-50 via-red-50/80 to-violet-50/40 flex items-center justify-between">
                <span className="text-sm font-semibold text-brand-700">
                  Total Pengeluaran
                </span>
                <span className="text-base font-bold text-red-600 tabular-nums">
                  {formatCurrency(totalExpenses)}
                </span>
              </div>
            )}
          </div>

          {/* Desktop: Table view */}
          <div className="hidden lg:block overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-brand-100 bg-brand-50/40">
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Tanggal
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Kategori
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Deskripsi
                  </th>
                  <th className="px-6 py-3.5 text-left text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Catatan
                  </th>
                  <th className="px-6 py-3.5 text-right text-xs font-semibold text-brand-500 uppercase tracking-wider">
                    Jumlah
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-brand-50">
                {expenses.map((expense) => (
                  <tr
                    key={expense.id}
                    className="hover:bg-red-50/20 transition-colors"
                  >
                    <td className="px-6 py-3.5 text-brand-500">
                      {formatDateShort(expense.date)}
                    </td>
                    <td className="px-6 py-3.5">
                      <span className="inline-flex rounded-full bg-violet-50 px-2.5 py-0.5 text-xs font-medium text-violet-700 border border-violet-100">
                        {EXPENSE_CATEGORIES.find(
                          (c) => c.value === expense.category
                        )?.label ?? expense.category}
                      </span>
                    </td>
                    <td className="px-6 py-3.5 font-medium text-brand-700">
                      {expense.description}
                    </td>
                    <td className="px-6 py-3.5 text-brand-400 text-xs italic">
                      {expense.notes || '-'}
                    </td>
                    <td className="px-6 py-3.5 text-right font-semibold text-red-600 tabular-nums">
                      -{formatCurrency(expense.amount)}
                    </td>
                  </tr>
                ))}
                {expenses.length === 0 && !expenseFetching && (
                  <tr>
                    <td colSpan={5}>
                      <EmptyState type="expense" />
                    </td>
                  </tr>
                )}
              </tbody>
              {expenseTotalItems > 0 && (
                <tfoot>
                  <tr className="border-t-2 border-red-100">
                    <td
                      colSpan={5}
                      className="px-0 py-0"
                    >
                      <div className="bg-gradient-to-r from-red-50 via-red-50/80 to-violet-50/40 px-6 py-4 flex items-center justify-between">
                        <span className="font-semibold text-brand-700">
                          Total Pengeluaran
                        </span>
                        <span className="text-lg font-bold text-red-600 tabular-nums">
                          {formatCurrency(totalExpenses)}
                        </span>
                      </div>
                    </td>
                  </tr>
                </tfoot>
              )}
            </table>
          </div>

          {/* Expense Pagination */}
          {expenseTotalPages > 1 && (
            <PaginationBar
              page={expensePage}
              totalPages={expenseTotalPages}
              totalItems={expenseTotalItems}
              perPage={ITEMS_PER_PAGE}
              fetching={expenseFetching}
              onPageChange={setExpensePage}
            />
          )}
        </div>
      )}

      {/* ── Add Expense Modal ── */}
      <Modal
        isOpen={showExpenseModal}
        onClose={() => setShowExpenseModal(false)}
        title="Tambah Pengeluaran"
      >
        <div className="space-y-5">
          {/* Category */}
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-brand-700">
              Kategori
            </label>
            <select
              value={expenseForm.category}
              onChange={(e) =>
                setExpenseForm((prev) => ({ ...prev, category: e.target.value }))
              }
              className="w-full rounded-xl border border-brand-200 bg-brand-50/30 py-3 px-4 text-sm text-brand-700 focus:border-brand-400 focus:ring-2 focus:ring-brand-200/50 focus:bg-white outline-none transition-all min-h-[48px] cursor-pointer"
            >
              {EXPENSE_CATEGORIES.map((cat) => (
                <option key={cat.value} value={cat.value}>
                  {cat.label}
                </option>
              ))}
            </select>
          </div>

          {/* Description */}
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-brand-700">
              Deskripsi
            </label>
            <input
              type="text"
              value={expenseForm.description}
              onChange={(e) =>
                setExpenseForm((prev) => ({
                  ...prev,
                  description: e.target.value,
                }))
              }
              placeholder="Contoh: Beli stok minyak goreng 50 karton"
              className="w-full rounded-xl border border-brand-200 bg-brand-50/30 py-3 px-4 text-sm text-brand-700 placeholder:text-brand-400 focus:border-brand-400 focus:ring-2 focus:ring-brand-200/50 focus:bg-white outline-none transition-all min-h-[48px]"
            />
          </div>

          {/* Amount */}
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-brand-700">
              Jumlah (Rp)
            </label>
            <div className="relative">
              <span className="absolute left-4 top-1/2 -translate-y-1/2 text-sm font-medium text-brand-400">
                Rp
              </span>
              <input
                type="number"
                min={0}
                value={expenseForm.amount}
                onChange={(e) =>
                  setExpenseForm((prev) => ({ ...prev, amount: e.target.value }))
                }
                placeholder="0"
                className="w-full rounded-xl border border-brand-200 bg-brand-50/30 py-3 pl-10 pr-4 text-sm text-brand-700 placeholder:text-brand-400 focus:border-brand-400 focus:ring-2 focus:ring-brand-200/50 focus:bg-white outline-none transition-all min-h-[48px] tabular-nums"
              />
            </div>
          </div>

          {/* Date */}
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-brand-700">
              Tanggal
            </label>
            <input
              type="date"
              value={expenseForm.date}
              onChange={(e) =>
                setExpenseForm((prev) => ({ ...prev, date: e.target.value }))
              }
              className="w-full rounded-xl border border-brand-200 bg-brand-50/30 py-3 px-4 text-sm text-brand-700 focus:border-brand-400 focus:ring-2 focus:ring-brand-200/50 focus:bg-white outline-none transition-all min-h-[48px]"
            />
          </div>

          {/* Notes */}
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-brand-700">
              Catatan{' '}
              <span className="font-normal text-brand-400">(opsional)</span>
            </label>
            <textarea
              value={expenseForm.notes}
              onChange={(e) =>
                setExpenseForm((prev) => ({ ...prev, notes: e.target.value }))
              }
              placeholder="Catatan tambahan..."
              rows={2}
              className="w-full rounded-xl border border-brand-200 bg-brand-50/30 py-3 px-4 text-sm text-brand-700 placeholder:text-brand-400 focus:border-brand-400 focus:ring-2 focus:ring-brand-200/50 focus:bg-white outline-none transition-all resize-none"
            />
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-3">
            <button
              onClick={() => setShowExpenseModal(false)}
              className="flex-1 rounded-xl border border-brand-200 px-4 py-3 text-sm font-medium text-brand-600 hover:bg-brand-50 transition-colors cursor-pointer min-h-[48px]"
            >
              Batal
            </button>
            <button
              onClick={handleAddExpense}
              disabled={
                !expenseForm.description ||
                !expenseForm.amount ||
                expenseSubmitting
              }
              className={cn(
                'flex-1 rounded-xl px-4 py-3 text-sm font-semibold transition-all min-h-[48px]',
                expenseForm.description && expenseForm.amount && !expenseSubmitting
                  ? 'bg-brand-600 text-white hover:bg-brand-700 cursor-pointer active:scale-[0.98] shadow-sm'
                  : 'bg-brand-100 text-brand-400 cursor-not-allowed'
              )}
            >
              {expenseSubmitting ? 'Menyimpan...' : 'Simpan'}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

/* ── Pagination Bar Component ── */
function PaginationBar({
  page,
  totalPages,
  totalItems,
  perPage,
  fetching,
  onPageChange,
}: {
  page: number;
  totalPages: number;
  totalItems: number;
  perPage: number;
  fetching: boolean;
  onPageChange: (p: number) => void;
}) {
  return (
    <div className="flex items-center justify-between border-t border-border px-4 lg:px-6 py-3.5 bg-surface/30">
      <p className="hidden sm:block text-sm text-brand-500">
        Menampilkan{' '}
        <span className="font-semibold text-brand-600">
          {(page - 1) * perPage + 1}-{Math.min(page * perPage, totalItems)}
        </span>{' '}
        dari{' '}
        <span className="font-semibold text-brand-600">{totalItems}</span>
      </p>
      <p className="sm:hidden text-xs text-brand-500">
        Hal{' '}
        <span className="font-semibold text-brand-600">{page}</span>/
        <span className="font-semibold text-brand-600">{totalPages}</span>
      </p>

      <div className="flex items-center gap-1">
        <button
          onClick={() => onPageChange(Math.max(1, page - 1))}
          disabled={page === 1 || fetching}
          className={cn(
            'flex h-8 w-8 items-center justify-center rounded-full transition-all',
            page === 1 || fetching
              ? 'text-brand-300 cursor-not-allowed'
              : 'text-brand-600 hover:bg-brand-100/60 hover:text-brand-700'
          )}
        >
          <ChevronLeft className="h-4 w-4" />
        </button>

        {Array.from({ length: totalPages }, (_, i) => i + 1)
          .filter((p) => {
            if (totalPages <= 5) return true;
            return Math.abs(p - page) <= 1 || p === 1 || p === totalPages;
          })
          .map((p, idx, arr) => (
            <span key={p} className="contents">
              {idx > 0 && arr[idx - 1] !== p - 1 && (
                <span className="text-xs text-brand-300 px-0.5 select-none">
                  ...
                </span>
              )}
              <button
                onClick={() => onPageChange(p)}
                disabled={fetching}
                className={cn(
                  'flex h-8 min-w-8 items-center justify-center rounded-full text-sm font-medium transition-all',
                  p === page
                    ? 'bg-brand-600 text-white shadow-sm'
                    : 'text-brand-600 hover:bg-brand-100/60'
                )}
              >
                {p}
              </button>
            </span>
          ))}

        <button
          onClick={() => onPageChange(Math.min(totalPages, page + 1))}
          disabled={page === totalPages || fetching}
          className={cn(
            'flex h-8 w-8 items-center justify-center rounded-full transition-all',
            page === totalPages || fetching
              ? 'text-brand-300 cursor-not-allowed'
              : 'text-brand-600 hover:bg-brand-100/60 hover:text-brand-700'
          )}
        >
          <ChevronRight className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

/* ── Empty State Component ── */
function EmptyState({ type }: { type: 'income' | 'expense' }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 px-6">
      <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-brand-50 mb-4">
        <Package className="h-8 w-8 text-brand-300" />
      </div>
      <p className="text-sm font-medium text-brand-500 mb-1">
        {type === 'income'
          ? 'Belum ada data pemasukan'
          : 'Belum ada data pengeluaran'}
      </p>
      <p className="text-xs text-brand-400 text-center max-w-[240px]">
        {type === 'income'
          ? 'Data pemasukan akan muncul setelah ada pesanan yang selesai dibayar'
          : 'Tambahkan pengeluaran pertama untuk mulai mencatat'}
      </p>
    </div>
  );
}
