'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import {
  RiArrowLeftLine,
  RiArrowUpLine,
  RiArrowDownLine,
  RiDownloadLine,
  RiFilterLine,
  RiFilterOffLine,
  RiSearchLine,
} 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 { useUserBalanceLogs, useBalanceSummary } 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',
};

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: number;
  userName?: string;
}

export default function UserBalanceLogs({ userId, userName }: Props) {
  const router = useRouter();
  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 };
    if (actionFilter) p.action = actionFilter;
    if (typeFilter) p.type_balance = typeFilter;
    return p;
  }, [page, actionFilter, typeFilter]);

  const { data, isLoading, isFetching } = useUserBalanceLogs(userId, params);
  const { data: summary, isLoading: summaryLoading } = useBalanceSummary(userId);

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

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

  const hasFilters = actionFilter || typeFilter;

  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-logs-user-${userId}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="sm" onClick={() => router.back()}>
          <RiArrowLeftLine className="size-4 mr-1" />
          Back
        </Button>
        <div>
          <h1 className="text-xl font-semibold">Balance History{userName ? `: ${userName}` : ''}</h1>
          <p className="text-sm text-muted-foreground">
            {total.toLocaleString()} log entries for user #{userId}
          </p>
        </div>
      </div>

      {!summaryLoading && summary && Array.isArray(summary) && summary.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
          {summary.map((item, i) => (
            <Card key={i}>
              <CardContent className="py-3 px-4 space-y-1">
                <p className="text-xs text-muted-foreground font-medium truncate">
                  {item.type_label ?? BALANCE_TYPE_LABELS[item.type] ?? item.type}
                </p>
                <p className="text-lg font-bold">{item.current_balance?.toLocaleString() ?? 0}</p>
                <div className="flex items-center gap-2 text-xs">
                  <span className="text-green-600">+{item.total_added?.toLocaleString() ?? 0}</span>
                  <span className="text-red-500">-{item.total_used?.toLocaleString() ?? 0}</span>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <div className="flex items-center justify-between">
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={() => setShowFilters(!showFilters)}>
            <RiFilterLine className="size-4 mr-1" />
            Filters
          </Button>
        </div>
        <Button variant="outline" size="sm" onClick={handleExportCsv} disabled={!logs.length}>
          <RiDownloadLine className="size-4 mr-1" />
          Export CSV
        </Button>
      </div>

      {showFilters && (
        <Card>
          <CardContent className="py-4">
            <div className="flex flex-wrap gap-3 items-end">
              <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">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">Network</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 for this user.
                    </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>
                        <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.social_network ?? '-'}</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>
  );
}
