'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { AlertTriangle, CheckCircle, Ban } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import ActionButton from '@/components/ui/ActionButton';
import { fraudApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

export default function FraudDetectionPage() {
  const [filters, setFilters] = useState({ search: '', severity: '', status: '' });
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['fraud-alerts', filters],
    queryFn: () => fraudApi.getAlerts(filters),
  });

  const acknowledgeMutation = useMutation({
    mutationFn: fraudApi.acknowledgeAlert,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['fraud-alerts'] });
      alert('Alert acknowledged');
    },
  });

  const blockUserMutation = useMutation({
    mutationFn: ({ userId, reason }: any) => fraudApi.blockUser(userId, { reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['fraud-alerts'] });
      alert('User blocked successfully');
    },
  });

  const handleAcknowledge = async (alert: any) => {
    await acknowledgeMutation.mutateAsync(alert.id);
  };

  const handleBlockUser = async (alert: any) => {
    if (confirm(`Block user ${alert.user?.email}?`)) {
      await blockUserMutation.mutateAsync({
        userId: alert.userId,
        reason: `Fraud alert: ${alert.ruleType}`,
      });
    }
  };

  const columns = [
    {
      key: 'severity',
      label: 'Severity',
      render: (alert: any) => (
        <Badge variant="status" status={alert.severity === 'HIGH' ? 'CANCELLED' : alert.severity === 'MEDIUM' ? 'PENDING' : 'CONFIRMED'}>
          {alert.severity}
        </Badge>
      ),
    },
    {
      key: 'ruleType',
      label: 'Rule Type',
      render: (alert: any) => (
        <div className="flex items-center gap-2">
          <AlertTriangle className="h-4 w-4 text-[rgb(20,113,76)]" />
          <span>{alert.ruleType}</span>
        </div>
      ),
    },
    {
      key: 'user',
      label: 'User',
      render: (alert: any) => (
        <div>
          <div className="font-medium">{alert.user?.fullName || 'N/A'}</div>
          <div className="text-sm text-muted-foreground">{alert.user?.email || 'N/A'}</div>
        </div>
      ),
    },
    {
      key: 'description',
      label: 'Description',
      render: (alert: any) => (
        <span className="text-sm">{alert.description || alert.details}</span>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (alert: any) => (
        <Badge variant="status" status={alert.acknowledged ? 'CONFIRMED' : 'PENDING'}>
          {alert.acknowledged ? 'Acknowledged' : 'Pending'}
        </Badge>
      ),
    },
    {
      key: 'createdAt',
      label: 'Detected',
      sortable: true,
      render: (alert: any) => formatDateTime(alert.createdAt),
    },
  ];

  const actions = [
    {
      label: 'Acknowledge',
      onClick: handleAcknowledge,
      variant: 'primary' as const,
      icon: CheckCircle,
      show: (alert: any) => !alert.acknowledged,
    },
    {
      label: 'Block User',
      onClick: handleBlockUser,
      variant: 'danger' as const,
      icon: Ban,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Fraud Detection</h1>
          <p className="text-muted-foreground">Monitor and manage fraud alerts</p>
        </div>
      </div>

      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search</label>
            <input
              type="text"
              placeholder="Search alerts..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
            />
          </div>
          <div>
            <label className="label">Severity</label>
            <select
              className="input"
              value={filters.severity}
              onChange={(e) => setFilters({ ...filters, severity: e.target.value })}
            >
              <option value="">All Severities</option>
              <option value="LOW">Low</option>
              <option value="MEDIUM">Medium</option>
              <option value="HIGH">High</option>
              <option value="CRITICAL">Critical</option>
            </select>
          </div>
          <div>
            <label className="label">Status</label>
            <select
              className="input"
              value={filters.status}
              onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            >
              <option value="">All Status</option>
              <option value="pending">Pending</option>
              <option value="acknowledged">Acknowledged</option>
            </select>
          </div>
        </div>
      </div>

      <DataTable
        data={data?.items || []}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No fraud alerts found"
      />
    </div>
  );
}
