import React, { useState } from 'react';
import { motion } from 'motion/react';
import { Button } from './ui/button';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Input } from './ui/input';
import { 
  ArrowUpRight, 
  ArrowDownRight, 
  Zap, 
  Users, 
  Smartphone,
  Wifi,
  CreditCard,
  Search,
  Filter,
  Download,
  Calendar
} from 'lucide-react';

interface Transaction {
  id: string;
  type: 'send' | 'receive' | 'bill' | 'savings' | 'topup' | 'group_payout';
  description: string;
  amount: number;
  date: string;
  status: 'completed' | 'pending' | 'failed';
  category: string;
  recipient?: string;
  reference: string;
  wallet: 'savings' | 'spend';
}

// Mock transaction data
const mockTransactions: Transaction[] = [
  {
    id: '1',
    type: 'receive',
    description: 'Money received from John Doe',
    amount: 150.00,
    date: '2024-02-28T10:30:00Z',
    status: 'completed',
    category: 'Transfer',
    recipient: 'John Doe',
    reference: 'TXN-2024-001',
    wallet: 'spend'
  },
  {
    id: '2',
    type: 'bill',
    description: 'Electricity bill payment',
    amount: -85.50,
    date: '2024-02-27T14:15:00Z',
    status: 'completed',
    category: 'Utilities',
    reference: 'ELC-2024-001',
    wallet: 'spend'
  },
  {
    id: '3',
    type: 'savings',
    description: 'Monthly savings deposit',
    amount: -200.00,
    date: '2024-02-26T09:00:00Z',
    status: 'completed',
    category: 'Savings',
    reference: 'SAV-2024-001',
    wallet: 'savings'
  },
  {
    id: '4',
    type: 'topup',
    description: 'Airtime purchase',
    amount: -25.00,
    date: '2024-02-25T16:45:00Z',
    status: 'completed',
    category: 'Telecom',
    reference: 'AIR-2024-002',
    wallet: 'spend'
  },
  {
    id: '5',
    type: 'group_payout',
    description: 'Group savings payout - Friends Circle',
    amount: 1000.00,
    date: '2024-02-24T11:20:00Z',
    status: 'completed',
    category: 'Group Savings',
    reference: 'GRP-2024-001',
    wallet: 'spend'
  },
  {
    id: '6',
    type: 'send',
    description: 'Money sent to Sarah Wilson',
    amount: -75.00,
    date: '2024-02-23T13:30:00Z',
    status: 'completed',
    category: 'Transfer',
    recipient: 'Sarah Wilson',
    reference: 'TXN-2024-002',
    wallet: 'spend'
  },
  {
    id: '7',
    type: 'bill',
    description: 'Mobile data bundle',
    amount: -40.00,
    date: '2024-02-22T08:15:00Z',
    status: 'pending',
    category: 'Telecom',
    reference: 'DAT-2024-003',
    wallet: 'spend'
  },
  {
    id: '8',
    type: 'receive',
    description: 'Refund from utility company',
    amount: 35.00,
    date: '2024-02-21T12:00:00Z',
    status: 'completed',
    category: 'Refund',
    reference: 'REF-2024-001',
    wallet: 'spend'
  }
];

export function TransactionHistory() {
  const [transactions] = useState<Transaction[]>(mockTransactions);
  const [filteredTransactions, setFilteredTransactions] = useState<Transaction[]>(mockTransactions);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');
  const [walletFilter, setWalletFilter] = useState('all');

  // Apply filters
  React.useEffect(() => {
    let filtered = transactions;

    // Search filter
    if (searchTerm) {
      filtered = filtered.filter(t => 
        t.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
        t.reference.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (t.recipient && t.recipient.toLowerCase().includes(searchTerm.toLowerCase()))
      );
    }

    // Status filter
    if (statusFilter !== 'all') {
      filtered = filtered.filter(t => t.status === statusFilter);
    }

    // Type filter
    if (typeFilter !== 'all') {
      filtered = filtered.filter(t => t.type === typeFilter);
    }

    // Wallet filter
    if (walletFilter !== 'all') {
      filtered = filtered.filter(t => t.wallet === walletFilter);
    }

    setFilteredTransactions(filtered);
  }, [searchTerm, statusFilter, typeFilter, walletFilter, transactions]);

  const getTransactionIcon = (type: string) => {
    switch (type) {
      case 'send': return <ArrowUpRight className="w-5 h-5 text-red-600" />;
      case 'receive': return <ArrowDownRight className="w-5 h-5 text-green-600" />;
      case 'bill': return <Zap className="w-5 h-5 text-yellow-600" />;
      case 'savings': return <CreditCard className="w-5 h-5 text-blue-600" />;
      case 'topup': return <Smartphone className="w-5 h-5 text-purple-600" />;
      case 'group_payout': return <Users className="w-5 h-5 text-green-600" />;
      default: return <CreditCard className="w-5 h-5 text-gray-600" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-100 text-green-800';
      case 'pending': return 'bg-yellow-100 text-yellow-800';
      case 'failed': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getWalletColor = (wallet: string) => {
    switch (wallet) {
      case 'savings': return 'bg-blue-100 text-blue-800';
      case 'spend': return 'bg-purple-100 text-purple-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getTotalByStatus = (status: string) => {
    return transactions.filter(t => t.status === status).length;
  };

  const getTotalAmount = () => {
    return transactions
      .filter(t => t.status === 'completed')
      .reduce((sum, t) => sum + Math.abs(t.amount), 0);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="space-y-6"
    >
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Transaction History</h2>
          <p className="text-gray-600">Track all your financial activities</p>
        </div>
        <Button variant="outline" className="flex items-center space-x-2">
          <Download className="w-4 h-4" />
          <span>Export</span>
        </Button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Volume</p>
                <p className="text-xl font-bold">${getTotalAmount().toLocaleString()}</p>
              </div>
              <CreditCard className="w-8 h-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Completed</p>
                <p className="text-xl font-bold text-green-600">{getTotalByStatus('completed')}</p>
              </div>
              <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                <ArrowDownRight className="w-4 h-4 text-green-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Pending</p>
                <p className="text-xl font-bold text-yellow-600">{getTotalByStatus('pending')}</p>
              </div>
              <div className="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                <Calendar className="w-4 h-4 text-yellow-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Failed</p>
                <p className="text-xl font-bold text-red-600">{getTotalByStatus('failed')}</p>
              </div>
              <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                <Zap className="w-4 h-4 text-red-600" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div className="md:col-span-2">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="Search transactions..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger>
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="completed">Completed</SelectItem>
                <SelectItem value="pending">Pending</SelectItem>
                <SelectItem value="failed">Failed</SelectItem>
              </SelectContent>
            </Select>
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger>
                <SelectValue placeholder="Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="send">Send Money</SelectItem>
                <SelectItem value="receive">Receive Money</SelectItem>
                <SelectItem value="bill">Bill Payment</SelectItem>
                <SelectItem value="savings">Savings</SelectItem>
                <SelectItem value="topup">Top Up</SelectItem>
                <SelectItem value="group_payout">Group Payout</SelectItem>
              </SelectContent>
            </Select>
            <Select value={walletFilter} onValueChange={setWalletFilter}>
              <SelectTrigger>
                <SelectValue placeholder="Wallet" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Wallets</SelectItem>
                <SelectItem value="savings">Savings Wallet</SelectItem>
                <SelectItem value="spend">Spend Wallet</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Transactions List */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Transactions ({filteredTransactions.length})</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {filteredTransactions.length === 0 ? (
              <div className="text-center py-8">
                <CreditCard className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">No transactions found</h3>
                <p className="text-gray-500">Try adjusting your search or filters</p>
              </div>
            ) : (
              filteredTransactions.map((transaction) => (
                <motion.div
                  key={transaction.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                >
                  <div className="flex items-center space-x-4">
                    <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-sm">
                      {getTransactionIcon(transaction.type)}
                    </div>
                    <div>
                      <p className="font-medium">{transaction.description}</p>
                      <div className="flex items-center space-x-2 mt-1">
                        <p className="text-sm text-gray-500">{formatDate(transaction.date)}</p>
                        <Badge className={getWalletColor(transaction.wallet)} variant="outline">
                          {transaction.wallet}
                        </Badge>
                      </div>
                      <p className="text-xs text-gray-400">{transaction.reference}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`font-semibold ${transaction.amount >= 0 ? 'text-green-600' : 'text-gray-900'}`}>
                      {transaction.amount >= 0 ? '+' : ''}${Math.abs(transaction.amount).toLocaleString()}
                    </p>
                    <Badge className={getStatusColor(transaction.status)} variant="outline">
                      {transaction.status}
                    </Badge>
                  </div>
                </motion.div>
              ))
            )}
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}