'use client';

import { useState, useMemo } from 'react';
import {
  RiSearchLine,
  RiFilterLine,
  RiFilterOffLine,
  RiArrowUpLine,
  RiArrowDownLine,
  RiDownloadLine,
} from '@remixicon/react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardHeader,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useAllBalanceLogs } from '../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' });
}

export default function BalanceLogsList() {
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  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 };
    if (search) p.search = search;
    if (actionFilter) p.action = actionFilter;
    if (typeFilter) p.type_balance = typeFilter;
    return p;
  }, [page, search, actionFilter, typeFilter]);

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

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

  const handleExportCsv = () => {
    if (!logs.length) return;
    const headers = ['ID', 'User', 'Action', 'Amount', 'Balance After', 'Type', 'Notes', 'Created By', 'Date'];
    const rows = logs.map((l) => [
      l.id,
      l.user_name,
      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-logs-page${page}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

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

  const hasFilters = search || actionFilter || typeFilter;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold">Balance Logs</h1>
          <p className="text-sm text-muted-foreground mt-1">
            View all balance changes across all users ({total.toLocaleString()} total entries)
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={() => setShowFilters(!showFilters)}>
            <RiFilterLine className="size-4 mr-1" />
            Filters
          </Button>
          <Button variant="outline" size="sm" onClick={handleExportCsv} disabled={!logs.length}>
            <RiDownloadLine className="size-4 mr-1" />
            Export CSV
          </Button>
        </div>
      </div>

      {showFilters && (
        <Card>
          <CardContent className="py-4">
            <div className="flex flex-wrap gap-3 items-end">
              <div className="flex-1 min-w-[200px]">
                <label className="text-xs font-medium text-muted-foreground mb-1 block">Search User</label>
                <div className="relative">
                  <RiSearchLine className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                  <Input
                    className="pl-9"
                    placeholder="Search by user name..."
                    value={search}
                    onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                  />
                </div>
              </div>
              <div className="min-w-[160px]">
                <label className="text-xs font-medium text-muted-foreground mb-1 block">Action</label>
                <select
                  className="w-full border rounded-md px-3 py-2 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-[180px]">
                <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-2 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-4 mr-1" />
                  Clear
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader className="py-0 px-0" />
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/40">
                  <TableHead className="w-16 h-10 font-semibold">ID</TableHead>
                  <TableHead className="h-10 font-semibold">User</TableHead>
                  <TableHead className="h-10 font-semibold">Action</TableHead>
                  <TableHead className="h-10 font-semibold text-right">Amount</TableHead>
                  <TableHead className="h-10 font-semibold text-right">Balance After</TableHead>
                  <TableHead className="h-10 font-semibold">Type</TableHead>
                  <TableHead className="h-10 font-semibold">Notes</TableHead>
                  <TableHead className="h-10 font-semibold">Created By</TableHead>
                  <TableHead className="h-10 font-semibold">Date</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-12">
                      <div className="flex items-center justify-center gap-2 text-muted-foreground">
                        <Spinner className="size-4 animate-spin" /> Loading logs...
                      </div>
                    </TableCell>
                  </TableRow>
                ) : logs.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-12 text-muted-foreground">
                      No balance logs found.
                    </TableCell>
                  </TableRow>
                ) : (
                  logs.map((log) => (
                    <TableRow key={log.id} className="hover:bg-muted/30">
                      <TableCell className="text-sm font-mono text-muted-foreground">{log.id}</TableCell>
                      <TableCell className="text-sm font-medium">{log.user_name ?? '-'}</TableCell>
                      <TableCell>
                        <Badge variant={ACTION_VARIANTS[log.action] ?? 'secondary'} className="text-xs">
                          {log.action}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-sm text-right font-mono">
                        <span className={`flex items-center justify-end 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-sm 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-sm text-muted-foreground max-w-[200px] truncate">
                        {log.notes?.note_string ?? '-'}
                      </TableCell>
                      <TableCell className="text-sm">{log.created_by_name ?? '-'}</TableCell>
                      <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
                        {formatDate(log.created_at)}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {lastPage > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Page {page} of {lastPage} ({total.toLocaleString()} entries)
          </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">
          <Spinner className="size-3 animate-spin" /> Refreshing...
        </div>
      )}
    </div>
  );
}
