'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
  CreditCard, Plus, Trash2, Edit, Search, ToggleLeft, ToggleRight,
  Smartphone, Wallet, Bitcoin, Building, Settings2,
  ShieldCheck, Database, Receipt, DollarSign, Clock,
  CheckCircle2, XCircle, RefreshCw, ArrowUpDown, Eye, TrendingUp,
  Loader2, Filter,
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

// ============ TYPES ============
interface PaymentGateway {
  id: string;
  name: string;
  slug: string;
  type: string;
  icon: string | null;
  description: string | null;
  config: string;
  instructions: string;
  isActive: boolean;
  sortOrder: number;
  isSystem: boolean;
  createdAt: string;
  updatedAt: string;
}

interface PaymentTransaction {
  id: string;
  userId: string;
  gatewayId: string;
  orderId: string | null;
  amount: number;
  currency: string;
  status: string;
  transactionId: string | null;
  gatewayResponse: string | null;
  metadata: string;
  createdAt: string;
  updatedAt: string;
  user: { id: string; name: string; email: string; avatar: string | null };
  gateway: { id: string; name: string; icon: string | null; type: string; slug: string };
}

interface TransactionStats {
  totalAmount: number;
  totalTransactions: number;
  completedAmount: number;
  completedCount: number;
  pendingAmount: number;
  pendingCount: number;
}

interface ConfigField {
  key: string;
  value: string;
}

// ============ HELPERS ============
const GATEWAY_TYPES = [
  { value: 'mobile_banking', label: 'Mobile Banking', labelBn: 'মোবাইল ব্যাংকিং', icon: Smartphone, color: 'bg-pink-100 text-pink-700 dark:bg-pink-950/30 dark:text-pink-400' },
  { value: 'card', label: 'Card', labelBn: 'কার্ড', icon: CreditCard, color: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400' },
  { value: 'crypto', label: 'Crypto', labelBn: 'ক্রিপ্টো', icon: Bitcoin, color: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400' },
  { value: 'digital_wallet', label: 'Digital Wallet', labelBn: 'ডিজিটাল ওয়ালেট', icon: Wallet, color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' },
  { value: 'custom', label: 'Custom', labelBn: 'কাস্টম', icon: Settings2, color: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400' },
];

const TRANSACTION_STATUSES = [
  { value: 'pending', label: 'Pending', labelBn: 'অপেক্ষমাণ', color: 'bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400', icon: Clock },
  { value: 'processing', label: 'Processing', labelBn: 'প্রক্রিয়াধীন', color: 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400', icon: RefreshCw },
  { value: 'completed', label: 'Completed', labelBn: 'সম্পন্ন', color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400', icon: CheckCircle2 },
  { value: 'failed', label: 'Failed', labelBn: 'ব্যর্থ', color: 'bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400', icon: XCircle },
  { value: 'refunded', label: 'Refunded', labelBn: 'ফেরত', color: 'bg-violet-100 text-violet-700 dark:bg-violet-950/30 dark:text-violet-400', icon: RefreshCw },
];

function getTypeConfig(type: string) {
  return GATEWAY_TYPES.find(t => t.value === type) || GATEWAY_TYPES[4];
}

function getStatusConfig(status: string) {
  return TRANSACTION_STATUSES.find(s => s.value === status) || TRANSACTION_STATUSES[0];
}

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

function parseConfig(configStr: string): ConfigField[] {
  try {
    const obj = JSON.parse(configStr || '{}');
    return Object.entries(obj).map(([key, value]) => ({
      key,
      value: String(value),
    }));
  } catch {
    return [];
  }
}

function configFieldsToJson(fields: ConfigField[]): string {
  const obj: Record<string, string> = {};
  fields.forEach(f => {
    if (f.key.trim()) obj[f.key.trim()] = f.value;
  });
  return JSON.stringify(obj);
}

// ============ AUTHENTICATED FETCH HELPER ============
function adminFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const token = typeof window !== 'undefined' ? useAppStore.getState().adminToken : null;
  const headers = new Headers(options.headers);
  if (token) headers.set('x-admin-token', token);
  if (!headers.has('Content-Type') && options.body) headers.set('Content-Type', 'application/json');
  return fetch(url, { ...options, headers });
}

// ============ GATEWAY FORM DIALOG ============
function GatewayFormDialog({
  gateway,
  open,
  onOpenChange,
  onSaved,
}: {
  gateway: PaymentGateway | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSaved: () => void;
}) {
  const { language } = useAppStore();
  const { toast } = useToast();
  const [name, setName] = useState('');
  const [slug, setSlug] = useState('');
  const [type, setType] = useState('custom');
  const [icon, setIcon] = useState('');
  const [description, setDescription] = useState('');
  const [configFields, setConfigFields] = useState<ConfigField[]>([{ key: '', value: '' }]);
  const [instructions, setInstructions] = useState('');
  const [isActive, setIsActive] = useState(false);
  const [sortOrder, setSortOrder] = useState(0);
  const [saving, setSaving] = useState(false);

  const isEdit = !!gateway;

  // Populate form when editing
  useEffect(() => {
    if (gateway) {
      setName(gateway.name);
      setSlug(gateway.slug);
      setType(gateway.type);
      setIcon(gateway.icon || '');
      setDescription(gateway.description || '');
      setConfigFields(parseConfig(gateway.config));
      setInstructions(gateway.instructions || '');
      setIsActive(gateway.isActive);
      setSortOrder(gateway.sortOrder);
    } else {
      setName('');
      setSlug('');
      setType('custom');
      setIcon('');
      setDescription('');
      setConfigFields([{ key: '', value: '' }]);
      setInstructions('');
      setIsActive(false);
      setSortOrder(0);
    }
  }, [gateway, open]);

  // Auto-generate slug from name
  const handleNameChange = (val: string) => {
    setName(val);
    if (!isEdit) {
      setSlug(slugify(val));
    }
  };

  const addConfigField = () => {
    setConfigFields([...configFields, { key: '', value: '' }]);
  };

  const removeConfigField = (index: number) => {
    setConfigFields(configFields.filter((_, i) => i !== index));
  };

  const updateConfigField = (index: number, field: 'key' | 'value', val: string) => {
    const updated = [...configFields];
    updated[index] = { ...updated[index], [field]: val };
    setConfigFields(updated);
  };

  const handleSave = async () => {
    if (!name.trim() || !slug.trim()) {
      toast({
        title: language === 'en' ? 'Missing Fields' : 'তথ্য অসম্পূর্ণ',
        description: language === 'en' ? 'Name and slug are required' : 'নাম এবং স্লাগ আবশ্যক',
        variant: 'destructive',
      });
      return;
    }

    setSaving(true);
    try {
      const payload = {
        name: name.trim(),
        slug: slug.trim(),
        type,
        icon: icon || null,
        description: description || null,
        config: configFieldsToJson(configFields),
        instructions,
        isActive,
        sortOrder,
        ...(isEdit ? { gatewayId: gateway.id } : {}),
      };

      const res = await adminFetch('/api/admin/payment-gateways', {
        method: isEdit ? 'PATCH' : 'POST',
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (data.success) {
        toast({
          title: language === 'en' ? 'Success' : 'সফল',
          description: isEdit
            ? (language === 'en' ? 'Gateway updated successfully' : 'গেটওয়ে আপডেট সফল')
            : (language === 'en' ? 'Gateway created successfully' : 'গেটওয়ে তৈরি সফল'),
        });
        onSaved();
        onOpenChange(false);
      } else {
        toast({
          title: language === 'en' ? 'Error' : 'ত্রুটি',
          description: data.error || 'Failed to save gateway',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Error' : 'ত্রুটি',
        description: language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি',
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  // Common emoji/icon options for quick selection
  const iconOptions = ['📱', '💳', '🅿️', '🟢', '₿', '🏦', '💰', '🔗', '🏪', '🔒', '✅', '🎁'];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <CreditCard className="h-5 w-5 text-primary" />
            {isEdit
              ? (language === 'en' ? 'Edit Gateway' : 'গেটওয়ে সম্পাদনা')
              : (language === 'en' ? 'Add Gateway' : 'গেটওয়ে যোগ করুন')}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Name */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Gateway Name' : 'গেটওয়ে নাম'} <span className="text-destructive">*</span>
            </Label>
            <Input
              value={name}
              onChange={(e) => handleNameChange(e.target.value)}
              placeholder={language === 'en' ? 'e.g., bKash, PayPal' : 'যেমন, বিকাশ, পেপ্যাল'}
            />
          </div>

          {/* Slug */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Slug' : 'স্লাগ'} <span className="text-destructive">*</span>
            </Label>
            <Input
              value={slug}
              onChange={(e) => setSlug(e.target.value)}
              placeholder="e.g., bkash, paypal"
              disabled={isEdit && gateway?.isSystem}
            />
            <p className="text-[10px] text-muted-foreground">
              {language === 'en' ? 'Auto-generated from name. Used as unique identifier.' : 'নাম থেকে স্বয়ংক্রিয়ভাবে তৈরি। অনন্য শনাক্তকারী হিসেবে ব্যবহৃত।'}
            </p>
          </div>

          {/* Type */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Gateway Type' : 'গেটওয়ে ধরন'}
            </Label>
            <Select value={type} onValueChange={setType}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {GATEWAY_TYPES.map((t) => (
                  <SelectItem key={t.value} value={t.value}>
                    <span className="flex items-center gap-2">
                      <t.icon className="h-4 w-4" />
                      {language === 'en' ? t.label : t.labelBn}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Icon */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Icon / Emoji' : 'আইকন / ইমোজি'}
            </Label>
            <div className="flex flex-wrap gap-2 mb-2">
              {iconOptions.map((emoji) => (
                <button
                  key={emoji}
                  type="button"
                  onClick={() => setIcon(emoji)}
                  className={`flex h-9 w-9 items-center justify-center rounded-lg border text-lg transition-all ${
                    icon === emoji
                      ? 'border-primary bg-primary/10 shadow-sm'
                      : 'border-border hover:border-primary/30'
                  }`}
                >
                  {emoji}
                </button>
              ))}
            </div>
            <Input
              value={icon}
              onChange={(e) => setIcon(e.target.value)}
              placeholder={language === 'en' ? 'Custom icon or emoji' : 'কাস্টম আইকন বা ইমোজি'}
            />
          </div>

          {/* Description */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Description' : 'বিবরণ'}
            </Label>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder={language === 'en' ? 'Brief description of this gateway' : 'এই গেটওয়ের সংক্ষিপ্ত বিবরণ'}
              rows={2}
            />
          </div>

          {/* Config Fields (Dynamic Key-Value) */}
          <div className="space-y-1.5">
            <div className="flex items-center justify-between">
              <Label className="text-xs font-medium">
                {language === 'en' ? 'Configuration Fields' : 'কনফিগারেশন ফিল্ড'}
              </Label>
              <Button type="button" variant="outline" size="sm" className="h-7 text-xs gap-1" onClick={addConfigField}>
                <Plus className="h-3 w-3" />
                {language === 'en' ? 'Add Field' : 'ফিল্ড যোগ করুন'}
              </Button>
            </div>
            <div className="space-y-2">
              {configFields.map((field, idx) => (
                <div key={idx} className="flex items-center gap-2">
                  <Input
                    value={field.key}
                    onChange={(e) => updateConfigField(idx, 'key', e.target.value)}
                    placeholder={language === 'en' ? 'Key (e.g., apiKey)' : 'কী (যেমন, apiKey)'}
                    className="flex-1"
                  />
                  <Input
                    value={field.value}
                    onChange={(e) => updateConfigField(idx, 'value', e.target.value)}
                    placeholder={language === 'en' ? 'Value' : 'মান'}
                    className="flex-1"
                    type={field.key.toLowerCase().includes('secret') || field.key.toLowerCase().includes('password') ? 'password' : 'text'}
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
                    onClick={() => removeConfigField(idx)}
                    disabled={configFields.length <= 1}
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </Button>
                </div>
              ))}
            </div>
            <p className="text-[10px] text-muted-foreground">
              {language === 'en'
                ? 'Add API key, secret, merchant ID, endpoint URL, etc.'
                : 'API কী, সিক্রেট, মার্চেন্ট আইডি, এন্ডপয়েন্ট URL ইত্যাদি যোগ করুন'}
            </p>
          </div>

          {/* Instructions */}
          <div className="space-y-1.5">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Payment Instructions (JSON)' : 'পেমেন্ট নির্দেশনা (JSON)'}
            </Label>
            <Textarea
              value={instructions}
              onChange={(e) => setInstructions(e.target.value)}
              placeholder={'{"number": "01XXXXXXXXX", "type": "Send Money"}'}
              rows={3}
              className="font-mono text-xs"
            />
            <p className="text-[10px] text-muted-foreground">
              {language === 'en'
                ? 'JSON format instructions shown to users at checkout'
                : 'চেকআউটে ব্যবহারকারীদের দেখানো JSON ফরম্যাট নির্দেশনা'}
            </p>
          </div>

          {/* Active Toggle & Sort Order */}
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <Switch checked={isActive} onCheckedChange={setIsActive} />
              <Label className="text-xs font-medium">
                {isActive
                  ? (language === 'en' ? 'Active' : 'সক্রিয়')
                  : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}
              </Label>
            </div>
            <div className="flex items-center gap-2">
              <Label className="text-xs font-medium">
                {language === 'en' ? 'Sort Order' : 'ক্রম'}
              </Label>
              <Input
                type="number"
                value={sortOrder}
                onChange={(e) => setSortOrder(parseInt(e.target.value) || 0)}
                className="w-20"
                min={0}
              />
            </div>
          </div>

          {/* Save Button */}
          <Button
            className="w-full bg-gradient-to-r from-orange-700 to-orange-500 font-semibold shadow-md hover:from-orange-800 hover:to-orange-600"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? (
              <span className="flex items-center gap-2">
                <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                {language === 'en' ? 'Saving...' : 'সংরক্ষণ হচ্ছে...'}
              </span>
            ) : (
              <span className="flex items-center gap-2">
                <CreditCard className="h-4 w-4" />
                {isEdit
                  ? (language === 'en' ? 'Update Gateway' : 'গেটওয়ে আপডেট করুন')
                  : (language === 'en' ? 'Create Gateway' : 'গেটওয়ে তৈরি করুন')}
              </span>
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ============ TRANSACTION DETAIL DIALOG ============
function TransactionDetailDialog({
  transaction,
  open,
  onOpenChange,
  onStatusUpdate,
}: {
  transaction: PaymentTransaction | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onStatusUpdate: () => void;
}) {
  const { language } = useAppStore();
  const { toast } = useToast();
  const [updatingStatus, setUpdatingStatus] = useState<string | null>(null);

  const handleStatusChange = async (newStatus: string) => {
    if (!transaction || newStatus === transaction.status) return;
    setUpdatingStatus(newStatus);
    try {
      const res = await adminFetch('/api/admin/payment-transactions', {
        method: 'PATCH',
        body: JSON.stringify({ transactionId: transaction.id, status: newStatus }),
      });
      const data = await res.json();
      if (data.success) {
        toast({
          title: language === 'en' ? 'Status Updated' : 'স্ট্যাটাস আপডেট',
          description: language === 'en'
            ? `Transaction status changed to ${newStatus}`
            : `লেনদেন স্ট্যাটাস ${newStatus} এ পরিবর্তিত হয়েছে`,
        });
        onStatusUpdate();
        onOpenChange(false);
      } else {
        toast({
          title: language === 'en' ? 'Error' : 'ত্রুটি',
          description: data.error || 'Failed to update status',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Error' : 'ত্রুটি',
        description: language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি',
        variant: 'destructive',
      });
    } finally {
      setUpdatingStatus(null);
    }
  };

  if (!transaction) return null;

  const statusConfig = getStatusConfig(transaction.status);
  const StatusIcon = statusConfig.icon;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Receipt className="h-5 w-5 text-primary" />
            {language === 'en' ? 'Transaction Details' : 'লেনদেন বিবরণ'}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Status Badge */}
          <div className="flex items-center justify-between">
            <Badge className={`text-xs gap-1.5 ${statusConfig.color}`}>
              <StatusIcon className="h-3 w-3" />
              {language === 'en' ? statusConfig.label : statusConfig.labelBn}
            </Badge>
            <span className="text-[10px] text-muted-foreground">
              {new Date(transaction.createdAt).toLocaleString()}
            </span>
          </div>

          <Separator />

          {/* Transaction Info */}
          <div className="space-y-2.5">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{language === 'en' ? 'Transaction ID' : 'লেনদেন আইডি'}</span>
              <span className="font-mono text-xs">{transaction.id.slice(0, 16)}...</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{language === 'en' ? 'Amount' : 'পরিমাণ'}</span>
              <span className="font-bold text-primary">৳{transaction.amount.toLocaleString()} {transaction.currency}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{language === 'en' ? 'User' : 'ব্যবহারকারী'}</span>
              <span className="font-medium">{transaction.user.name}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{language === 'en' ? 'Email' : 'ইমেইল'}</span>
              <span className="text-xs">{transaction.user.email}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">{language === 'en' ? 'Gateway' : 'গেটওয়ে'}</span>
              <span className="font-medium flex items-center gap-1.5">
                {transaction.gateway.icon && <span>{transaction.gateway.icon}</span>}
                {transaction.gateway.name}
              </span>
            </div>
            {transaction.orderId && (
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">{language === 'en' ? 'Order ID' : 'অর্ডার আইডি'}</span>
                <span className="font-mono text-xs">{transaction.orderId.slice(0, 16)}...</span>
              </div>
            )}
            {transaction.transactionId && (
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">{language === 'en' ? 'Gateway Txn ID' : 'গেটওয়ে লেনদেন আইডি'}</span>
                <span className="font-mono text-xs">{transaction.transactionId}</span>
              </div>
            )}
          </div>

          {/* Gateway Response */}
          {transaction.gatewayResponse && (
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">
                {language === 'en' ? 'Gateway Response' : 'গেটওয়ে রেসপন্স'}
              </Label>
              <div className="rounded-lg bg-accent/30 p-2 max-h-32 overflow-y-auto custom-scrollbar">
                <pre className="text-[10px] font-mono whitespace-pre-wrap break-all">
                  {(() => {
                    try { return JSON.stringify(JSON.parse(transaction.gatewayResponse), null, 2); }
                    catch { return transaction.gatewayResponse; }
                  })()}
                </pre>
              </div>
            </div>
          )}

          {/* Metadata */}
          {transaction.metadata && transaction.metadata !== '{}' && (
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">
                {language === 'en' ? 'Metadata' : 'মেটাডেটা'}
              </Label>
              <div className="rounded-lg bg-accent/30 p-2 max-h-24 overflow-y-auto custom-scrollbar">
                <pre className="text-[10px] font-mono whitespace-pre-wrap break-all">
                  {(() => {
                    try { return JSON.stringify(JSON.parse(transaction.metadata), null, 2); }
                    catch { return transaction.metadata; }
                  })()}
                </pre>
              </div>
            </div>
          )}

          <Separator />

          {/* Update Status */}
          <div className="space-y-2">
            <Label className="text-xs font-medium">
              {language === 'en' ? 'Update Status' : 'স্ট্যাটাস আপডেট করুন'}
            </Label>
            <div className="flex gap-1.5 flex-wrap">
              {TRANSACTION_STATUSES.map((s) => {
                const SIcon = s.icon;
                return (
                  <Button
                    key={s.value}
                    variant={transaction.status === s.value ? 'default' : 'outline'}
                    size="sm"
                    className={`text-[10px] gap-1 h-7 ${transaction.status === s.value ? s.color : ''}`}
                    onClick={() => handleStatusChange(s.value)}
                    disabled={transaction.status === s.value || updatingStatus !== null}
                  >
                    {updatingStatus === s.value ? (
                      <span className="h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent" />
                    ) : (
                      <SIcon className="h-3 w-3" />
                    )}
                    {language === 'en' ? s.label : s.labelBn}
                  </Button>
                );
              })}
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ============ MAIN ADMIN PAYMENTS COMPONENT ============
export default function AdminPayments() {
  const { language } = useAppStore();
  const { toast } = useToast();

  // Sub-tab state
  const [activeSubTab, setActiveSubTab] = useState<'gateways' | 'transactions'>('gateways');

  // Gateway state
  const [gateways, setGateways] = useState<PaymentGateway[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingGateway, setEditingGateway] = useState<PaymentGateway | null>(null);
  const [deleteGateway, setDeleteGateway] = useState<PaymentGateway | null>(null);
  const [seeding, setSeeding] = useState(false);

  // Transaction state
  const [transactions, setTransactions] = useState<PaymentTransaction[]>([]);
  const [transactionStats, setTransactionStats] = useState<TransactionStats | null>(null);
  const [txLoading, setTxLoading] = useState(false);
  const [txFilterStatus, setTxFilterStatus] = useState('all');
  const [txSearchQuery, setTxSearchQuery] = useState('');
  const [selectedTransaction, setSelectedTransaction] = useState<PaymentTransaction | null>(null);
  const [txDetailOpen, setTxDetailOpen] = useState(false);

  // Fetch gateways
  const fetchGateways = useCallback(async () => {
    try {
      const res = await adminFetch('/api/admin/payment-gateways');
      const data = await res.json();
      if (data.success) setGateways(data.gateways);
    } catch (err) {
      console.error('Failed to fetch gateways:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch transactions
  const fetchTransactions = useCallback(async () => {
    setTxLoading(true);
    try {
      const params = new URLSearchParams();
      if (txFilterStatus && txFilterStatus !== 'all') params.set('status', txFilterStatus);
      params.set('limit', '100');
      const res = await adminFetch(`/api/admin/payment-transactions?${params.toString()}`);
      const data = await res.json();
      if (data.success) {
        setTransactions(data.transactions);
        setTransactionStats(data.stats);
      }
    } catch (err) {
      console.error('Failed to fetch transactions:', err);
    } finally {
      setTxLoading(false);
    }
  }, [txFilterStatus]);

  useEffect(() => { fetchGateways(); }, [fetchGateways]);
  useEffect(() => {
    if (activeSubTab === 'transactions') fetchTransactions();
  }, [activeSubTab, fetchTransactions]);

  // Gateway handlers
  const handleToggleActive = async (gateway: PaymentGateway) => {
    try {
      const res = await adminFetch('/api/admin/payment-gateways', {
        method: 'PATCH',
        body: JSON.stringify({ gatewayId: gateway.id, isActive: !gateway.isActive }),
      });
      const data = await res.json();
      if (data.success) {
        fetchGateways();
        toast({
          title: language === 'en' ? 'Status Updated' : 'স্ট্যাটাস আপডেট',
          description: `${gateway.name} ${!gateway.isActive ? (language === 'en' ? 'activated' : 'সক্রিয়') : (language === 'en' ? 'deactivated' : 'নিষ্ক্রিয়')}`,
        });
      }
    } catch (err) {
      console.error('Failed to toggle gateway:', err);
    }
  };

  const handleDelete = async () => {
    if (!deleteGateway) return;
    try {
      const res = await adminFetch('/api/admin/payment-gateways', {
        method: 'DELETE',
        body: JSON.stringify({ gatewayId: deleteGateway.id }),
      });
      const data = await res.json();
      if (data.success) {
        fetchGateways();
        toast({
          title: language === 'en' ? 'Deleted' : 'মুছে ফেলা হয়েছে',
          description: `${deleteGateway.name} ${language === 'en' ? 'deleted' : 'মুছে ফেলা হয়েছে'}`,
        });
      } else {
        toast({
          title: language === 'en' ? 'Error' : 'ত্রুটি',
          description: data.error,
          variant: 'destructive',
        });
      }
    } catch (err) {
      console.error('Failed to delete gateway:', err);
    } finally {
      setDeleteGateway(null);
    }
  };

  const handleSeed = async () => {
    setSeeding(true);
    try {
      const res = await adminFetch('/api/payment-gateways/seed', { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        fetchGateways();
        toast({
          title: language === 'en' ? 'Gateways Seeded' : 'গেটওয়ে তৈরি হয়েছে',
          description: data.message,
        });
      }
    } catch (err) {
      console.error('Failed to seed gateways:', err);
    } finally {
      setSeeding(false);
    }
  };

  const handleEdit = (gateway: PaymentGateway) => {
    setEditingGateway(gateway);
    setDialogOpen(true);
  };

  const handleAdd = () => {
    setEditingGateway(null);
    setDialogOpen(true);
  };

  const handleDialogClose = (open: boolean) => {
    setDialogOpen(open);
    if (!open) setEditingGateway(null);
  };

  // Filter gateways
  const filtered = gateways.filter((gw) => {
    const matchesSearch = gw.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      gw.slug.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = filterType === 'all' || gw.type === filterType;
    return matchesSearch && matchesType;
  });

  // Filter transactions by search
  const filteredTransactions = transactions.filter((tx) => {
    if (!txSearchQuery) return true;
    const q = txSearchQuery.toLowerCase();
    return (
      tx.user.name.toLowerCase().includes(q) ||
      tx.user.email.toLowerCase().includes(q) ||
      tx.gateway.name.toLowerCase().includes(q) ||
      tx.id.toLowerCase().includes(q) ||
      (tx.transactionId && tx.transactionId.toLowerCase().includes(q))
    );
  });

  // Stats
  const activeCount = gateways.filter(g => g.isActive).length;
  const inactiveCount = gateways.filter(g => !g.isActive).length;
  const customCount = gateways.filter(g => !g.isSystem).length;

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold flex items-center gap-2">
            <CreditCard className="h-5 w-5 text-primary" />
            {language === 'en' ? 'Payment Gateways' : 'পেমেন্ট গেটওয়ে'}
          </h2>
          <p className="text-sm text-muted-foreground mt-1">
            {language === 'en'
              ? 'Manage payment methods, gateway configurations and transactions'
              : 'পেমেন্ট পদ্ধতি, গেটওয়ে কনফিগারেশন এবং লেনদেন পরিচালনা করুন'}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {activeSubTab === 'gateways' && (
            <>
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5"
                onClick={handleSeed}
                disabled={seeding}
              >
                <Database className="h-3.5 w-3.5" />
                {seeding
                  ? (language === 'en' ? 'Seeding...' : 'তৈরি হচ্ছে...')
                  : (language === 'en' ? 'Seed Defaults' : 'ডিফল্ট তৈরি করুন')}
              </Button>
              <Button
                className="gap-1.5 bg-gradient-to-r from-orange-700 to-orange-500 shadow-md hover:from-orange-800 hover:to-orange-600"
                onClick={handleAdd}
              >
                <Plus className="h-4 w-4" />
                {language === 'en' ? 'Add Gateway' : 'গেটওয়ে যোগ করুন'}
              </Button>
            </>
          )}
          {activeSubTab === 'transactions' && (
            <Button
              variant="outline"
              size="sm"
              className="gap-1.5"
              onClick={fetchTransactions}
              disabled={txLoading}
            >
              <RefreshCw className={`h-3.5 w-3.5 ${txLoading ? 'animate-spin' : ''}`} />
              {language === 'en' ? 'Refresh' : 'রিফ্রেশ'}
            </Button>
          )}
        </div>
      </div>

      {/* Sub-Tabs */}
      <div className="flex gap-1.5 border-b pb-0">
        <button
          onClick={() => setActiveSubTab('gateways')}
          className={`relative flex items-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors ${
            activeSubTab === 'gateways'
              ? 'text-primary'
              : 'text-muted-foreground hover:text-foreground'
          }`}
        >
          <CreditCard className="h-4 w-4" />
          {language === 'en' ? 'Gateways' : 'গেটওয়ে'}
          <Badge variant="secondary" className="text-[10px] ml-1">{gateways.length}</Badge>
          {activeSubTab === 'gateways' && (
            <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
          )}
        </button>
        <button
          onClick={() => setActiveSubTab('transactions')}
          className={`relative flex items-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors ${
            activeSubTab === 'transactions'
              ? 'text-primary'
              : 'text-muted-foreground hover:text-foreground'
          }`}
        >
          <Receipt className="h-4 w-4" />
          {language === 'en' ? 'Transactions' : 'লেনদেন'}
          {transactionStats && (
            <Badge variant="secondary" className="text-[10px] ml-1">
              {transactionStats.totalTransactions}
            </Badge>
          )}
          {activeSubTab === 'transactions' && (
            <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
          )}
        </button>
      </div>

      {/* ============ GATEWAYS SUB-TAB ============ */}
      {activeSubTab === 'gateways' && (
        <>
          {/* Stats */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {[
              { label: language === 'en' ? 'Total' : 'মোট', value: gateways.length, icon: CreditCard, color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30' },
              { label: language === 'en' ? 'Active' : 'সক্রিয়', value: activeCount, icon: ToggleRight, color: 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30' },
              { label: language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়', value: inactiveCount, icon: ToggleLeft, color: 'text-amber-600 bg-amber-50 dark:bg-amber-950/30' },
              { label: language === 'en' ? 'Custom' : 'কাস্টম', value: customCount, icon: Settings2, color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30' },
            ].map((stat, i) => (
              <Card key={i} className="transition-shadow hover:shadow-md">
                <CardContent className="p-4 flex items-center gap-3">
                  <div className={`flex h-9 w-9 items-center justify-center rounded-xl ${stat.color}`}>
                    <stat.icon className="h-4 w-4" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold">{stat.value}</p>
                    <p className="text-[10px] text-muted-foreground">{stat.label}</p>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Filters */}
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder={language === 'en' ? 'Search gateways...' : 'গেটওয়ে খুঁজুন...'}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <div className="flex gap-1.5 overflow-x-auto pb-1">
              <Button
                variant={filterType === 'all' ? 'default' : 'outline'}
                size="sm"
                className="shrink-0 text-xs"
                onClick={() => setFilterType('all')}
              >
                {language === 'en' ? 'All' : 'সব'}
              </Button>
              {GATEWAY_TYPES.map((t) => (
                <Button
                  key={t.value}
                  variant={filterType === t.value ? 'default' : 'outline'}
                  size="sm"
                  className="shrink-0 text-xs gap-1"
                  onClick={() => setFilterType(t.value)}
                >
                  <t.icon className="h-3 w-3" />
                  {language === 'en' ? t.label : t.labelBn}
                </Button>
              ))}
            </div>
          </div>

          {/* Gateway Cards */}
          {filtered.length === 0 ? (
            <Card>
              <CardContent className="py-16 text-center">
                <CreditCard className="h-12 w-12 mx-auto text-muted-foreground/30 mb-3" />
                <p className="text-sm text-muted-foreground">
                  {language === 'en' ? 'No payment gateways found' : 'কোনো পেমেন্ট গেটওয়ে পাওয়া যায়নি'}
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  {language === 'en'
                    ? 'Click "Seed Defaults" to add default gateways or "Add Gateway" to create a custom one'
                    : 'ডিফল্ট গেটওয়ে যোগ করতে "ডিফল্ট তৈরি করুন" ক্লিক করুন অথবা কাস্টম তৈরি করতে "গেটওয়ে যোগ করুন" ক্লিক করুন'}
                </p>
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {filtered.map((gw) => {
                const typeConfig = getTypeConfig(gw.type);
                const TypeIcon = typeConfig.icon;
                const parsedConfig = parseConfig(gw.config);
                const configCount = parsedConfig.filter(f => f.key.trim()).length;

                return (
                  <Card
                    key={gw.id}
                    className={`transition-all duration-200 hover:shadow-lg ${
                      gw.isActive
                        ? 'border-primary/20 shadow-sm'
                        : 'border-border/50 opacity-75'
                    }`}
                  >
                    <CardHeader className="pb-2">
                      <div className="flex items-start justify-between">
                        <div className="flex items-center gap-3">
                          <div className={`flex h-11 w-11 items-center justify-center rounded-xl text-xl ${
                            gw.isActive
                              ? 'bg-primary/10'
                              : 'bg-muted'
                          }`}>
                            {gw.icon || <CreditCard className="h-5 w-5 text-muted-foreground" />}
                          </div>
                          <div>
                            <CardTitle className="text-sm font-bold">{gw.name}</CardTitle>
                            <div className="flex items-center gap-1.5 mt-1">
                              <Badge className={`text-[9px] gap-1 ${typeConfig.color}`}>
                                <TypeIcon className="h-2.5 w-2.5" />
                                {language === 'en' ? typeConfig.label : typeConfig.labelBn}
                              </Badge>
                              {gw.isSystem && (
                                <Badge variant="outline" className="text-[9px] gap-1">
                                  <ShieldCheck className="h-2.5 w-2.5" />
                                  {language === 'en' ? 'System' : 'সিস্টেম'}
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                        <Switch
                          checked={gw.isActive}
                          onCheckedChange={() => handleToggleActive(gw)}
                          className="scale-75"
                        />
                      </div>
                    </CardHeader>
                    <CardContent className="pt-0">
                      {gw.description && (
                        <p className="text-xs text-muted-foreground line-clamp-2 mb-3">
                          {gw.description}
                        </p>
                      )}

                      {/* Config preview */}
                      {configCount > 0 && (
                        <div className="rounded-lg bg-accent/30 p-2 mb-3">
                          <p className="text-[10px] font-medium text-muted-foreground mb-1">
                            {language === 'en' ? 'Configuration' : 'কনফিগারেশন'} ({configCount} {language === 'en' ? 'fields' : 'ফিল্ড'})
                          </p>
                          <div className="space-y-0.5">
                            {parsedConfig.filter(f => f.key.trim()).slice(0, 3).map((field, i) => (
                              <div key={i} className="flex items-center gap-1 text-[10px]">
                                <span className="font-medium text-foreground">{field.key}:</span>
                                <span className="text-muted-foreground">
                                  {field.key.toLowerCase().includes('secret') || field.key.toLowerCase().includes('password')
                                    ? '••••••••'
                                    : (field.value.length > 20 ? field.value.slice(0, 20) + '...' : field.value)}
                                </span>
                              </div>
                            ))}
                            {configCount > 3 && (
                              <p className="text-[10px] text-muted-foreground">
                                +{configCount - 3} {language === 'en' ? 'more' : 'আরও'}
                              </p>
                            )}
                          </div>
                        </div>
                      )}

                      {/* Footer */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-1.5">
                          <Badge
                            variant={gw.isActive ? 'default' : 'secondary'}
                            className={`text-[9px] ${
                              gw.isActive
                                ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400'
                                : 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400'
                            }`}
                          >
                            {gw.isActive
                              ? (language === 'en' ? 'Active' : 'সক্রিয়')
                              : (language === 'en' ? 'Inactive' : 'নিষ্ক্রিয়')}
                          </Badge>
                          <span className="text-[9px] text-muted-foreground">
                            #{gw.sortOrder}
                          </span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-7 w-7"
                            onClick={() => handleEdit(gw)}
                            title={language === 'en' ? 'Edit' : 'সম্পাদনা'}
                          >
                            <Edit className="h-3.5 w-3.5" />
                          </Button>
                          {!gw.isSystem && (
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-7 w-7 text-muted-foreground hover:text-destructive"
                              onClick={() => setDeleteGateway(gw)}
                              title={language === 'en' ? 'Delete' : 'মুছুন'}
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          )}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </>
      )}

      {/* ============ TRANSACTIONS SUB-TAB ============ */}
      {activeSubTab === 'transactions' && (
        <>
          {/* Transaction Stats */}
          {transactionStats && (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {[
                {
                  label: language === 'en' ? 'Total Revenue' : 'মোট আয়',
                  value: `৳${transactionStats.totalAmount.toLocaleString()}`,
                  icon: DollarSign,
                  color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30',
                },
                {
                  label: language === 'en' ? 'Completed' : 'সম্পন্ন',
                  value: `৳${transactionStats.completedAmount.toLocaleString()}`,
                  subtitle: `${transactionStats.completedCount} ${language === 'en' ? 'transactions' : 'লেনদেন'}`,
                  icon: CheckCircle2,
                  color: 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30',
                },
                {
                  label: language === 'en' ? 'Pending' : 'অপেক্ষমাণ',
                  value: `৳${transactionStats.pendingAmount.toLocaleString()}`,
                  subtitle: `${transactionStats.pendingCount} ${language === 'en' ? 'transactions' : 'লেনদেন'}`,
                  icon: Clock,
                  color: 'text-amber-600 bg-amber-50 dark:bg-amber-950/30',
                },
                {
                  label: language === 'en' ? 'Total Transactions' : 'মোট লেনদেন',
                  value: transactionStats.totalTransactions,
                  icon: Receipt,
                  color: 'text-orange-600 bg-orange-50 dark:bg-orange-950/30',
                },
              ].map((stat, i) => (
                <Card key={i} className="transition-shadow hover:shadow-md">
                  <CardContent className="p-4 flex items-center gap-3">
                    <div className={`flex h-9 w-9 items-center justify-center rounded-xl ${stat.color}`}>
                      <stat.icon className="h-4 w-4" />
                    </div>
                    <div>
                      <p className="text-lg font-bold sm:text-2xl">{stat.value}</p>
                      <p className="text-[10px] text-muted-foreground">{stat.label}</p>
                      {'subtitle' in stat && stat.subtitle && (
                        <p className="text-[9px] text-muted-foreground/70">{stat.subtitle}</p>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          {/* Transaction Filters */}
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder={language === 'en' ? 'Search by user, email, gateway...' : 'ব্যবহারকারী, ইমেইল, গেটওয়ে খুঁজুন...'}
                value={txSearchQuery}
                onChange={(e) => setTxSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <div className="flex gap-1.5 overflow-x-auto pb-1">
              <Button
                variant={txFilterStatus === 'all' ? 'default' : 'outline'}
                size="sm"
                className="shrink-0 text-xs gap-1"
                onClick={() => setTxFilterStatus('all')}
              >
                <Filter className="h-3 w-3" />
                {language === 'en' ? 'All' : 'সব'}
              </Button>
              {TRANSACTION_STATUSES.map((s) => {
                const SIcon = s.icon;
                return (
                  <Button
                    key={s.value}
                    variant={txFilterStatus === s.value ? 'default' : 'outline'}
                    size="sm"
                    className="shrink-0 text-xs gap-1"
                    onClick={() => setTxFilterStatus(s.value)}
                  >
                    <SIcon className="h-3 w-3" />
                    {language === 'en' ? s.label : s.labelBn}
                  </Button>
                );
              })}
            </div>
          </div>

          {/* Transactions Table */}
          {txLoading ? (
            <div className="flex items-center justify-center py-20">
              <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            </div>
          ) : filteredTransactions.length === 0 ? (
            <Card>
              <CardContent className="py-16 text-center">
                <Receipt className="h-12 w-12 mx-auto text-muted-foreground/30 mb-3" />
                <p className="text-sm text-muted-foreground">
                  {language === 'en' ? 'No payment transactions found' : 'কোনো পেমেন্ট লেনদেন পাওয়া যায়নি'}
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  {language === 'en'
                    ? 'Transactions will appear here when users make payments'
                    : 'ব্যবহারকারীরা পেমেন্ট করলে লেনদেন এখানে দেখা যাবে'}
                </p>
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardContent className="p-0">
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="text-xs">{language === 'en' ? 'Transaction' : 'লেনদেন'}</TableHead>
                        <TableHead className="text-xs hidden sm:table-cell">{language === 'en' ? 'User' : 'ব্যবহারকারী'}</TableHead>
                        <TableHead className="text-xs">{language === 'en' ? 'Gateway' : 'গেটওয়ে'}</TableHead>
                        <TableHead className="text-xs">{language === 'en' ? 'Amount' : 'পরিমাণ'}</TableHead>
                        <TableHead className="text-xs">{language === 'en' ? 'Status' : 'স্ট্যাটাস'}</TableHead>
                        <TableHead className="text-xs hidden md:table-cell">{language === 'en' ? 'Date' : 'তারিখ'}</TableHead>
                        <TableHead className="text-xs">{language === 'en' ? 'Actions' : 'কার্যক্রম'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredTransactions.map((tx) => {
                        const sc = getStatusConfig(tx.status);
                        const SIcon = sc.icon;
                        return (
                          <TableRow key={tx.id}>
                            <TableCell>
                              <div>
                                <p className="text-xs font-mono">{tx.id.slice(0, 10)}...</p>
                                {tx.transactionId && (
                                  <p className="text-[10px] text-muted-foreground mt-0.5">
                                    Ref: {tx.transactionId.length > 12 ? tx.transactionId.slice(0, 12) + '...' : tx.transactionId}
                                  </p>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="hidden sm:table-cell">
                              <div className="flex items-center gap-2">
                                <div className="flex h-7 w-7 items-center justify-center rounded-full bg-primary/10 text-[10px] font-bold text-primary shrink-0">
                                  {tx.user.name.charAt(0).toUpperCase()}
                                </div>
                                <div className="min-w-0">
                                  <p className="text-xs font-medium truncate">{tx.user.name}</p>
                                  <p className="text-[10px] text-muted-foreground truncate">{tx.user.email}</p>
                                </div>
                              </div>
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-1.5">
                                {tx.gateway.icon && <span className="text-sm">{tx.gateway.icon}</span>}
                                <span className="text-xs font-medium">{tx.gateway.name}</span>
                              </div>
                            </TableCell>
                            <TableCell>
                              <p className="text-sm font-bold">৳{tx.amount.toLocaleString()}</p>
                              <p className="text-[10px] text-muted-foreground">{tx.currency}</p>
                            </TableCell>
                            <TableCell>
                              <Badge className={`text-[9px] gap-1 ${sc.color}`}>
                                <SIcon className="h-2.5 w-2.5" />
                                {language === 'en' ? sc.label : sc.labelBn}
                              </Badge>
                            </TableCell>
                            <TableCell className="hidden md:table-cell">
                              <span className="text-xs text-muted-foreground">
                                {new Date(tx.createdAt).toLocaleDateString()}
                              </span>
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-7 w-7"
                                  onClick={() => {
                                    setSelectedTransaction(tx);
                                    setTxDetailOpen(true);
                                  }}
                                  title={language === 'en' ? 'View Details' : 'বিবরণ দেখুন'}
                                >
                                  <Eye className="h-3.5 w-3.5" />
                                </Button>
                                {(tx.status === 'pending' || tx.status === 'processing') && (
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-950/30"
                                    onClick={async () => {
                                      try {
                                        const res = await adminFetch('/api/admin/payment-transactions', {
                                          method: 'PATCH',
                                          body: JSON.stringify({ transactionId: tx.id, status: 'completed' }),
                                        });
                                        const data = await res.json();
                                        if (data.success) {
                                          fetchTransactions();
                                          toast({
                                            title: language === 'en' ? 'Payment Approved' : 'পেমেন্ট অনুমোদিত',
                                            description: `৳${tx.amount} ${language === 'en' ? 'marked as completed' : 'সম্পন্ন হিসেবে চিহ্নিত'}`,
                                          });
                                        }
                                      } catch {
                                        toast({ title: 'Error', variant: 'destructive' });
                                      }
                                    }}
                                    title={language === 'en' ? 'Approve' : 'অনুমোদন'}
                                  >
                                    <CheckCircle2 className="h-3.5 w-3.5" />
                                  </Button>
                                )}
                                {(tx.status === 'pending' || tx.status === 'processing') && (
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30"
                                    onClick={async () => {
                                      try {
                                        const res = await adminFetch('/api/admin/payment-transactions', {
                                          method: 'PATCH',
                                          body: JSON.stringify({ transactionId: tx.id, status: 'failed' }),
                                        });
                                        const data = await res.json();
                                        if (data.success) {
                                          fetchTransactions();
                                          toast({
                                            title: language === 'en' ? 'Payment Rejected' : 'পেমেন্ট প্রত্যাখ্যাত',
                                            description: `৳${tx.amount} ${language === 'en' ? 'marked as failed' : 'ব্যর্থ হিসেবে চিহ্নিত'}`,
                                            variant: 'destructive',
                                          });
                                        }
                                      } catch {
                                        toast({ title: 'Error', variant: 'destructive' });
                                      }
                                    }}
                                    title={language === 'en' ? 'Reject' : 'প্রত্যাখ্যান'}
                                  >
                                    <XCircle className="h-3.5 w-3.5" />
                                  </Button>
                                )}
                              </div>
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}

      {/* Add/Edit Gateway Dialog */}
      <GatewayFormDialog
        gateway={editingGateway}
        open={dialogOpen}
        onOpenChange={handleDialogClose}
        onSaved={fetchGateways}
      />

      {/* Delete Gateway Confirmation */}
      <AlertDialog open={!!deleteGateway} onOpenChange={(open) => !open && setDeleteGateway(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {language === 'en' ? 'Delete Payment Gateway' : 'পেমেন্ট গেটওয়ে মুছুন'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {language === 'en'
                ? `Are you sure you want to delete "${deleteGateway?.name}"? This action cannot be undone.`
                : `আপনি কি নিশ্চিত "${deleteGateway?.name}" মুছে ফেলতে চান? এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না।`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>
              {language === 'en' ? 'Cancel' : 'বাতিল'}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {language === 'en' ? 'Delete' : 'মুছুন'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Transaction Detail Dialog */}
      <TransactionDetailDialog
        transaction={selectedTransaction}
        open={txDetailOpen}
        onOpenChange={setTxDetailOpen}
        onStatusUpdate={fetchTransactions}
      />
    </div>
  );
}
