'use client';

import { useMemo } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { useActivityLog } from '../../hooks/useActivityLog';
import {
  AccountLog,
  BalanceRequestLog,
  SubscriptionHistoryLog,
} from '@/network/apis/dashboard/activityLog/type';

// ── Helpers ───────────────────────────────────────────────────────────────────

const formatDate = (dateString: string | null | undefined) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
};

const actionColorMap: Record<string, 'success' | 'warning' | 'destructive'> = {
  create: 'success',
  created: 'success',
  Add: 'success',
  update: 'warning',
  updated: 'warning',
  upgraded: 'warning',
  request: 'destructive',
};

// ── Unified row type ──────────────────────────────────────────────────────────

type RowSource = 'Account' | 'Balance' | 'Subscription';

type UnifiedRow = {
  key: string;
  id: number;
  source: RowSource;
  performedBy: string;
  user: string;
  action: string;
  description: string;
  details: string;
  amount: string | null;
  balanceAfter: string | null;
  date: string;
};

const sourceColorMap: Record<RowSource, 'primary' | 'warning' | 'success'> = {
  Account: 'primary',
  Balance: 'warning',
  Subscription: 'success',
};

function normalizeAccountLog(log: AccountLog): UnifiedRow {
  return {
    key: `account-${log.id}`,
    id: log.id,
    source: 'Account',
    performedBy: log.performed_by_name || '-',
    user: log.user_name || '-',
    action: log.action,
    description: log.action_description,
    details: log.fields.length > 0 ? `${log.fields.length} fields` : '-',
    amount: null,
    balanceAfter: null,
    date: formatDate(log.created_at),
  };
}

function normalizeBalanceLog(log: BalanceRequestLog): UnifiedRow {
  return {
    key: `balance-${log.id}`,
    id: log.id,
    source: 'Balance',
    performedBy: log.created_by_name || '-',
    user: log.user_name || '-',
    action: log.action,
    description: log.type_balance.replace(/_/g, ' '),
    details: log.notes?.note_string || '-',
    amount: log.amount > 0 ? `+${log.amount}` : String(log.amount),
    balanceAfter: log.balance_after.toLocaleString(),
    date: '-',
  };
}

function normalizeSubscriptionLog(log: SubscriptionHistoryLog): UnifiedRow {
  const from = log.old_package?.name ?? '-';
  const to = log.new_package?.name ?? '-';
  return {
    key: `subscription-${log.id}`,
    id: log.id,
    source: 'Subscription',
    performedBy: String(log.created_by),
    user: '-',
    action: log.action,
    description: `${from} → ${to}`,
    details: log.price_difference != null ? `Price diff: ${log.price_difference}` : '-',
    amount: null,
    balanceAfter: null,
    date: formatDate(log.effective_date ?? log.created_at),
  };
}

// ── Columns ───────────────────────────────────────────────────────────────────

const columns = [
  'ID',
  'Type',
  'Performed By',
  'User',
  'Action',
  'Description',
  'Details',
  'Amount',
  'Balance After',
  'Date',
];

// ── Root Component ────────────────────────────────────────────────────────────

export function ActivityLogList() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const page = Number(searchParams?.get('page') || 1);

  const { data, isLoading } = useActivityLog({
    accountPage: page,
    balancePage: page,
    subscriptionPage: page,
  });

  const rows = useMemo<UnifiedRow[]>(() => {
    const accountRows = (data?.account_logs?.items ?? []).map(normalizeAccountLog);
    const balanceRows = (data?.balance_request_logs?.items ?? []).map(normalizeBalanceLog);
    const subscriptionRows = (data?.subscription_history?.items ?? []).map(normalizeSubscriptionLog);
    return [...accountRows, ...balanceRows, ...subscriptionRows];
  }, [data]);

  const totalPages = useMemo(() => {
    return Math.max(
      data?.account_logs?.total_pages ?? 1,
      data?.balance_request_logs?.total_pages ?? 1,
      data?.subscription_history?.total_pages ?? 1,
    );
  }, [data]);

  const handlePageChange = (p: number) => {
    const params = new URLSearchParams(searchParams?.toString());
    params.set('page', String(p));
    router.push(`?${params.toString()}`);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Activity Log</CardTitle>
      </CardHeader>

      <CardContent className="overflow-x-auto p-0">
        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Spinner className="size-6 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <Table className="min-w-max">
            <TableHeader>
              <TableRow className="bg-accent/60">
                {columns.map((col) => (
                  <TableHead key={col} className="min-w-[120px] h-10 whitespace-nowrap">
                    {col}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.length > 0 ? (
                rows.map((row) => (
                  <TableRow key={row.key}>
                    <TableCell className="whitespace-nowrap">{row.id}</TableCell>
                    <TableCell className="whitespace-nowrap">
                      <Badge variant={sourceColorMap[row.source]} appearance="outline">
                        {row.source}
                      </Badge>
                    </TableCell>
                    <TableCell className="whitespace-nowrap">{row.performedBy}</TableCell>
                    <TableCell className="whitespace-nowrap">{row.user}</TableCell>
                    <TableCell className="whitespace-nowrap">
                      <Badge
                        variant={actionColorMap[row.action] ?? 'secondary'}
                        appearance="outline"
                      >
                        {row.action}
                      </Badge>
                    </TableCell>
                    <TableCell className="whitespace-nowrap text-sm">{row.description}</TableCell>
                    <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                      {row.details}
                    </TableCell>
                    <TableCell className="whitespace-nowrap">
                      {row.amount != null ? (
                        <span className={row.amount.startsWith('+') ? 'text-success' : 'text-destructive'}>
                          {row.amount}
                        </span>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell className="whitespace-nowrap">{row.balanceAfter ?? '-'}</TableCell>
                    <TableCell className="whitespace-nowrap text-sm">{row.date}</TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={columns.length} className="text-center py-8 text-muted-foreground">
                    No activity logs found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </CardContent>

      {totalPages > 1 && (
        <CardFooter className="justify-center">
          <PaginationComponent
            currentPage={page}
            totalPages={totalPages}
            onPageChange={handlePageChange}
          />
        </CardFooter>
      )}
    </Card>
  );
}
