'use client';

import { useState, useMemo } from 'react';
import {
  RiArrowUpLine,
  RiArrowDownLine,
  RiDownloadLine,
  RiFilterLine,
  RiFilterOffLine,
} from '@remixicon/react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useAllBalanceLogs } from '@/modules/balance-logs/hooks';

const BALANCE_TYPE_LABELS: Record<string, string> = {
  requests_balance: 'Reports',
  search_balance: 'Search',
  social_listening_balance: 'Social Listening',
  lookalike_balance: 'Lookalike',
  mynetwork_balance: 'Network',
  campaign_balance: 'Campaign Mgmt',
  competitor_analysis_balance: 'Competitor Analysis',
  phone_number_balance: 'Phone Number',
  media_plan_balance: 'Media Plan',
  media_plan_creators_balance: 'Media Plan Creators',
};

const ACTION_VARIANTS: Record<string, 'success' | 'destructive' | 'info' | 'warning' | 'secondary'> = {
  Add: 'success',
  add: 'success',
  request: 'info',
  api_deduct: 'destructive',
  mynetwork_add: 'success',
  deduct: 'destructive',
};

function formatDate(dateStr: string) {
  if (!dateStr) return '-';
  const d = new Date(dateStr);
  return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) +
    ' ' + d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
}

interface Props {
  userId: string;
}

export function UserBalanceHistory({ userId }: Props) {
  const [page, setPage] = useState(1);
  const [actionFilter, setActionFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [showFilters, setShowFilters] = useState(false);

  const params = useMemo(() => {
    const p: Record<string, unknown> = { page, per_page: 15, user_id: userId };
    if (actionFilter) p.action = actionFilter;
    if (typeFilter) p.type_balance = typeFilter;
    return p;
  }, [page, actionFilter, typeFilter, userId]);

  const { data, isLoading, isFetching } = useAllBalanceLogs(params);

  const logs = data?.data ?? [];
  const lastPage = data?.last_page ?? 1;
  const total = data?.total ?? 0;

  const hasFilters = actionFilter || typeFilter;

  const clearFilters = () => {
    setActionFilter('');
    setTypeFilter('');
    setPage(1);
  };

  const handleExportCsv = () => {
    if (!logs.length) return;
    const headers = ['ID', 'Action', 'Amount', 'Balance After', 'Type', 'Notes', 'Created By', 'Date'];
    const rows = logs.map((l) => [
      l.id,
      l.action,
      l.amount,
      l.balance_after,
      BALANCE_TYPE_LABELS[l.type_balance] ?? l.type_balance,
      l.notes?.note_string ?? '',
      l.created_by_name ?? '',
      formatDate(l.created_at),
    ]);
    const csv = [headers, ...rows].map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `balance-history-user-${userId}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="rounded-2xl border border-slate-200 bg-white shadow-sm">
      <div className="p-4 sm:p-6 text-sm">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-semibold">
            Balance History {total > 0 && <span className="text-muted-foreground font-normal">({total.toLocaleString()} entries)</span>}
          </h3>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => setShowFilters(!showFilters)}>
              <RiFilterLine className="size-3.5 mr-1" />
              Filters
            </Button>
            <Button variant="outline" size="sm" onClick={handleExportCsv} disabled={!logs.length}>
              <RiDownloadLine className="size-3.5 mr-1" />
              CSV
            </Button>
          </div>
        </div>

        {showFilters && (
          <div className="flex flex-wrap gap-3 items-end mb-4 p-3 bg-muted/30 rounded-lg">
            <div className="min-w-[140px]">
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Action</label>
              <select
                className="w-full border rounded-md px-3 py-1.5 text-sm bg-background"
                value={actionFilter}
                onChange={(e) => { setActionFilter(e.target.value); setPage(1); }}
              >
                <option value="">All Actions</option>
                <option value="Add">Add</option>
                <option value="request">Request</option>
                <option value="api_deduct">API Deduct</option>
                <option value="mynetwork_add">Network Add</option>
                <option value="deduct">Deduct</option>
              </select>
            </div>
            <div className="min-w-[160px]">
              <label className="text-xs font-medium text-muted-foreground mb-1 block">Balance Type</label>
              <select
                className="w-full border rounded-md px-3 py-1.5 text-sm bg-background"
                value={typeFilter}
                onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }}
              >
                <option value="">All Types</option>
                {Object.entries(BALANCE_TYPE_LABELS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
            </div>
            {hasFilters && (
              <Button variant="ghost" size="sm" onClick={clearFilters}>
                <RiFilterOffLine className="size-3.5 mr-1" />
                Clear
              </Button>
            )}
          </div>
        )}

        <div className="overflow-x-auto rounded-lg border">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/40">
                <TableHead className="w-14 h-9 text-xs font-semibold">ID</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Action</TableHead>
                <TableHead className="h-9 text-xs font-semibold text-right">Amount</TableHead>
                <TableHead className="h-9 text-xs font-semibold text-right">Balance After</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Type</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Notes</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Network</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Created By</TableHead>
                <TableHead className="h-9 text-xs font-semibold">Date</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-8">
                    <div className="flex items-center justify-center gap-2 text-muted-foreground">
                      <Spinner className="size-4 animate-spin" /> Loading balance history...
                    </div>
                  </TableCell>
                </TableRow>
              ) : logs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                    No balance history found for this user.
                  </TableCell>
                </TableRow>
              ) : (
                logs.map((log) => (
                  <TableRow key={log.id} className="hover:bg-muted/30">
                    <TableCell className="text-xs font-mono text-muted-foreground">{log.id}</TableCell>
                    <TableCell>
                      <Badge variant={ACTION_VARIANTS[log.action] ?? 'secondary'} className="text-xs">
                        {log.action}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-xs text-right font-mono">
                      <span className={`inline-flex items-center gap-1 ${log.amount >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                        {log.amount >= 0 ? <RiArrowUpLine className="size-3" /> : <RiArrowDownLine className="size-3" />}
                        {Math.abs(log.amount).toLocaleString()}
                      </span>
                    </TableCell>
                    <TableCell className="text-xs text-right font-mono">{log.balance_after?.toLocaleString() ?? '-'}</TableCell>
                    <TableCell>
                      <Badge variant="mono" className="text-xs">
                        {BALANCE_TYPE_LABELS[log.type_balance] ?? log.type_balance}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground max-w-[150px] truncate">
                      {log.notes?.note_string ?? '-'}
                    </TableCell>
                    <TableCell className="text-xs">{log.social_network ?? '-'}</TableCell>
                    <TableCell className="text-xs">{log.created_by_name ?? '-'}</TableCell>
                    <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                      {formatDate(log.created_at)}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>

        {lastPage > 1 && (
          <div className="flex items-center justify-between mt-3">
            <p className="text-xs text-muted-foreground">
              Page {page} of {lastPage}
            </p>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
                Previous
              </Button>
              <Button variant="outline" size="sm" disabled={page >= lastPage} onClick={() => setPage((p) => p + 1)}>
                Next
              </Button>
            </div>
          </div>
        )}

        {isFetching && !isLoading && (
          <div className="flex items-center gap-2 text-xs text-muted-foreground mt-2">
            <Spinner className="size-3 animate-spin" /> Refreshing...
          </div>
        )}
      </div>
    </div>
  );
}
