import React, { useState, useEffect } from 'react';
import bankService from '../services/bankService';
import {
    CreditCard,
    Plus,
    ArrowUpRight,
    ArrowDownLeft,
    History,
    Building2,
    Loader2,
    X,
    Filter,
    Download,
    Star,
    Wallet
} from 'lucide-react';
import { clsx } from 'clsx';

const Banking = () => {
    const [accounts, setAccounts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedAccount, setSelectedAccount] = useState(null);
    const [transactions, setTransactions] = useState([]);
    const [fetchingTransactions, setFetchingTransactions] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [newAccount, setNewAccount] = useState({
        bankName: '',
        accountName: '',
        accountNumber: '',
        openingBalance: 0,
        isDefault: false
    });

    useEffect(() => {
        fetchAccounts();
    }, []);

    useEffect(() => {
        if (selectedAccount) {
            fetchTransactions(selectedAccount.id);
        }
    }, [selectedAccount]);

    const fetchAccounts = async () => {
        setLoading(true);
        try {
            const res = await bankService.getAccounts();
            setAccounts(res.data);
            if (res.data.length > 0 && !selectedAccount) {
                const defaultAcc = res.data.find(a => a.isDefault) || res.data[0];
                setSelectedAccount(defaultAcc);
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const fetchTransactions = async (accountId) => {
        setFetchingTransactions(true);
        try {
            const res = await bankService.getTransactions(accountId);
            setTransactions(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setFetchingTransactions(false);
        }
    };

    const handleCreateAccount = async (e) => {
        e.preventDefault();
        try {
            await bankService.createAccount(newAccount);
            setIsModalOpen(false);
            fetchAccounts();
            setNewAccount({ bankName: '', accountName: '', accountNumber: '', openingBalance: 0, isDefault: false });
        } catch (err) {
            alert(err.response?.data?.error || 'Failed to create account');
        }
    };

    const handleSetDefault = async (id) => {
        try {
            await bankService.setDefault(id);
            fetchAccounts();
        } catch (err) {
            console.error(err);
        }
    };

    if (loading) return (
        <div className="flex flex-col items-center justify-center p-24 gap-4 animate-in fade-in">
            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading accounts...</p>
        </div>
    );

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <Building2 className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">Banking</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">Accounts</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap truncate">{accounts.length} Accounts</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={() => setIsModalOpen(true)}
                    className="w-full md:w-auto btn-primary flex items-center justify-center gap-2 px-8 h-12 lg:h-14"
                >
                    <Plus className="w-4 h-4 shrink-0" />
                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Add Account</span>
                </button>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                {/* Left: Account Cards */}
                <div className="lg:col-span-4 space-y-6">
                    <h2 className="text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.25em] ml-2">Your Accounts</h2>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-4 sm:gap-6">
                        {accounts.map(account => (
                            <button
                                key={account.id}
                                onClick={() => setSelectedAccount(account)}
                                className={clsx(
                                    "text-left p-6 sm:p-8 rounded-[2rem] sm:rounded-[2.5rem] border transition-all duration-500 relative overflow-hidden group",
                                    selectedAccount?.id === account.id
                                        ? "bg-slate-900 dark:bg-primary border-slate-900 dark:border-primary shadow-2xl shadow-primary/30 active-card scale-[1.02] sm:scale-100"
                                        : "premium-card bg-white dark:bg-slate-900 border-slate-100 dark:border-slate-800/50 hover:border-primary/20 shadow-sm"
                                )}
                            >
                                <div className="relative z-10 flex flex-col h-full gap-4 sm:gap-6">
                                    <div className="flex justify-between items-start">
                                        <div className={clsx(
                                            "p-3 sm:p-4 rounded-xl sm:rounded-2xl transition-all duration-500",
                                            selectedAccount?.id === account.id ? "bg-white/10 text-white" : "bg-primary/5 text-primary"
                                        )}>
                                            <Wallet className="w-5 h-5 sm:w-6 sm:h-6" />
                                        </div>
                                        {account.isDefault && (
                                            <div className={clsx(
                                                "px-2 sm:px-3 py-1 rounded-full text-[8px] sm:text-[9px] font-black uppercase tracking-widest border",
                                                selectedAccount?.id === account.id ? "bg-white/10 text-white border-white/20" : "bg-emerald-500/10 text-emerald-500 border-emerald-500/20"
                                            )}>
                                                Primary
                                            </div>
                                        )}
                                    </div>
                                    <div>
                                        <h3 className={clsx(
                                            "font-black text-sm sm:text-base uppercase tracking-tight truncate",
                                            selectedAccount?.id === account.id ? "text-white" : "text-slate-800 dark:text-slate-200"
                                        )}>
                                            {account.bankName}
                                        </h3>
                                        <p className={clsx(
                                            "text-[9px] sm:text-[10px] font-black uppercase tracking-widest mt-1",
                                            selectedAccount?.id === account.id ? "text-white/40" : "text-slate-400 dark:text-slate-600"
                                        )}>
                                            {account.accountNumber}
                                        </p>
                                    </div>
                                    <div className="mt-1 sm:mt-2">
                                        <p className={clsx(
                                            "text-[8px] sm:text-[9px] font-black uppercase tracking-[0.2em]",
                                            selectedAccount?.id === account.id ? "text-white/40" : "text-slate-400 dark:text-slate-500"
                                        )}>Current Balance</p>
                                        <p className={clsx(
                                            "text-xl sm:text-2xl font-black tracking-tighter mt-1",
                                            selectedAccount?.id === account.id ? "text-white" : "text-primary dark:text-primary"
                                        )}>
                                            <span className="text-[10px] opacity-60 mr-1">KES</span>
                                            {Number(account.currentBalance).toLocaleString()}
                                        </p>
                                    </div>
                                </div>
                                {selectedAccount?.id === account.id && (
                                    <div className="absolute -right-8 -bottom-8 w-32 h-32 bg-white/5 rounded-full blur-3xl" />
                                )}
                            </button>
                        ))}
                    </div>
                </div>

                {/* Right: Transactions Ledger */}
                <div className="lg:col-span-8">
                    <div className="premium-card overflow-hidden min-h-[400px] sm:min-h-[600px] flex flex-col">
                        <div className="p-6 sm:p-10 border-b border-slate-100 dark:border-slate-800/50 flex flex-col xl:flex-row xl:items-center justify-between gap-6">
                            <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                                <div className="p-3 sm:p-4 bg-slate-50 dark:bg-slate-900 rounded-xl sm:rounded-2xl border border-slate-100 dark:border-slate-800 shrink-0">
                                    <History className="w-5 h-5 text-slate-400 shrink-0" />
                                </div>
                                <div className="min-w-0">
                                    <h2 className="font-black text-slate-800 dark:text-white uppercase tracking-[0.15em] text-[10px] sm:text-[11px] truncate">Transaction History</h2>
                                    <p className="text-[9px] sm:text-[10px] text-slate-400 dark:text-slate-500 font-bold uppercase mt-1 tracking-widest truncate">{selectedAccount?.bankName} — Activity</p>
                                </div>
                            </div>
                            <div className="flex items-center gap-2 sm:gap-3 w-full xl:w-auto overflow-x-auto pb-1 xl:pb-0 scrollbar-none">
                                <button className="p-3 bg-slate-50 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800/50 rounded-2xl text-slate-400 hover:text-primary transition-all shrink-0">
                                    <Filter className="w-5 h-5 shrink-0" />
                                </button>
                                <button className="p-3 bg-slate-50 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800/50 rounded-2xl text-slate-400 hover:text-primary transition-all shrink-0">
                                    <Download className="w-5 h-5 shrink-0" />
                                </button>
                                {!selectedAccount?.isDefault && (
                                    <button
                                        onClick={() => handleSetDefault(selectedAccount.id)}
                                        className="flex-1 xl:flex-none flex items-center justify-center gap-2 bg-emerald-500/10 text-emerald-500 px-6 h-12 rounded-2xl text-[10px] sm:text-[11px] font-black uppercase tracking-widest hover:bg-emerald-500/20 transition-all border border-emerald-500/10 shrink-0"
                                    >
                                        <Star className="w-3.5 h-3.5 sm:w-4 sm:h-4 shrink-0" />
                                        <span className="whitespace-nowrap">Set Primary</span>
                                    </button>
                                )}
                            </div>
                        </div>

                        <div className="flex-1 overflow-x-auto overflow-y-hidden">
                            <table className="w-full text-left min-w-[900px]">
                                <thead>
                                    <tr className="bg-slate-50/20 dark:bg-slate-900/20">
                                        <th className="px-6 sm:px-10 py-5 sm:py-6 text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Date & Time</th>
                                        <th className="px-6 sm:px-10 py-5 sm:py-6 text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Description</th>
                                        <th className="px-6 sm:px-10 py-5 sm:py-6 text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Method</th>
                                        <th className="px-6 sm:px-10 py-5 sm:py-6 text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Amount</th>
                                        <th className="px-6 sm:px-10 py-5 sm:py-6 text-[10px] sm:text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Balance</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                                    {fetchingTransactions ? (
                                        <tr>
                                            <td colSpan="5" className="p-20 sm:p-32 text-center">
                                                <div className="flex flex-col items-center gap-4">
                                                    <Loader2 className="w-10 h-10 animate-spin text-primary/40 shrink-0" />
                                                    <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Loading transactions...</p>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : transactions.length === 0 ? (
                                        <tr>
                                            <td colSpan="5" className="p-20 sm:p-32 text-center text-slate-400 dark:text-slate-600 font-black uppercase text-[10px] tracking-[0.2em] opacity-50">No Transactions Found</td>
                                        </tr>
                                    ) : transactions.map(tx => (
                                        <tr key={tx.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300 group">
                                            <td className="px-6 sm:px-10 py-5 sm:py-6">
                                                <div className="flex flex-col whitespace-nowrap">
                                                    <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{new Date(tx.transactionDate).toLocaleDateString()}</span>
                                                    <span className="text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-widest">{new Date(tx.transactionDate).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                                                </div>
                                            </td>
                                            <td className="px-6 sm:px-10 py-5 sm:py-6">
                                                <div className="flex items-center gap-4 min-w-0">
                                                    <div className={clsx(
                                                        "p-2.5 rounded-xl border transition-all duration-300 shrink-0",
                                                        tx.type === 'Credit' ? "bg-emerald-500/10 text-emerald-500 border-emerald-500/10" : "bg-rose-500/10 text-rose-500 border-rose-500/10"
                                                    )}>
                                                        {tx.type === 'Credit' ? <ArrowDownLeft className="w-4 h-4 shrink-0" /> : <ArrowUpRight className="w-4 h-4 shrink-0" />}
                                                    </div>
                                                    <div className="min-w-0">
                                                        <p className="text-sm font-black text-slate-800 dark:text-white tracking-tight uppercase truncate max-w-[200px]">{tx.description}</p>
                                                        {tx.reference && <p className="text-[9px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest mt-0.5 truncate max-w-[150px]">Ref: {tx.reference}</p>}
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 sm:px-10 py-5 sm:py-6">
                                                <div className="inline-flex px-3 py-1 bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-full whitespace-nowrap">
                                                    <span className="text-[9px] font-black text-slate-500 dark:text-slate-400 uppercase tracking-widest">{tx.module}</span>
                                                </div>
                                            </td>
                                            <td className="px-6 sm:px-10 py-5 sm:py-6">
                                                <span className={clsx(
                                                    "text-sm font-black tracking-tight whitespace-nowrap",
                                                    tx.type === 'Credit' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                                )}>
                                                    {tx.type === 'Credit' ? '+' : '-'} {Number(tx.amount).toLocaleString()}
                                                </span>
                                            </td>
                                            <td className="px-6 sm:px-10 py-5 sm:py-6 text-right">
                                                <span className="text-sm font-black text-slate-400 dark:text-slate-600 tracking-tight whitespace-nowrap">
                                                    <span className="text-[9px] mr-1 opacity-60 font-black tracking-normal">KES</span>
                                                    {Number(tx.balanceAfter).toLocaleString()}
                                                </span>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-xl rounded-[2rem] sm:rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card flex flex-col max-h-[95vh]">
                        <div className="absolute top-0 left-0 w-full h-1.5 sm:h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-4 sm:gap-5 shrink-0">
                            <div className="p-3.5 sm:p-4 bg-primary rounded-xl sm:rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Building2 className="w-6 h-6 sm:w-7 sm:h-7 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight truncate">Add Bank Account</h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter account details</p>
                            </div>
                        </div>

                        <form onSubmit={handleCreateAccount} className="flex-1 overflow-y-auto px-6 sm:px-10 py-6 space-y-8 custom-scrollbar">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-8">
                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Bank Name</label>
                                    <div className="relative group">
                                        <Building2 className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                        <input
                                            required
                                            placeholder="Standard Chartered Bank"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={newAccount.bankName}
                                            onChange={e => setNewAccount({ ...newAccount, bankName: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Account Holder Name</label>
                                    <input
                                        required
                                        placeholder="Delight Office Solutions"
                                        className="premium-input h-12 sm:h-14"
                                        value={newAccount.accountName}
                                        onChange={e => setNewAccount({ ...newAccount, accountName: e.target.value })}
                                    />
                                </div>
                                <div className="sm:col-span-2 space-y-2">
                                    <label className="premium-label">Account Number</label>
                                    <div className="relative group">
                                        <CreditCard className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                        <input
                                            required
                                            placeholder="0110XXXXXXXX"
                                            className="premium-input !pl-12 h-12 sm:h-14"
                                            value={newAccount.accountNumber}
                                            onChange={e => setNewAccount({ ...newAccount, accountNumber: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <label className="premium-label">Opening Balance</label>
                                    <input
                                        type="number"
                                        className="premium-input !font-black !text-lg italic tracking-tight h-12 sm:h-14"
                                        value={newAccount.openingBalance}
                                        onChange={e => setNewAccount({ ...newAccount, openingBalance: e.target.value })}
                                    />
                                </div>
                                <div className="flex items-end h-12 sm:h-14">
                                    <label className="flex items-center gap-4 p-4 bg-slate-50/50 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800 rounded-2xl cursor-pointer hover:bg-white dark:hover:bg-slate-900 transition-all group w-full shrink-0">
                                        <div className="relative flex items-center shrink-0">
                                            <input
                                                type="checkbox"
                                                className="w-5 h-5 rounded-lg border-2 border-slate-200 dark:border-slate-700 text-primary focus:ring-primary/20 cursor-pointer transition-all shrink-0"
                                                checked={newAccount.isDefault}
                                                onChange={e => setNewAccount({ ...newAccount, isDefault: e.target.checked })}
                                            />
                                        </div>
                                        <div className="flex flex-col min-w-0">
                                            <span className="text-[10px] font-black text-slate-800 dark:text-white uppercase tracking-widest leading-none truncate">Set as Default</span>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                                <button
                                    type="button"
                                    onClick={() => setIsModalOpen(false)}
                                    className="flex-1 py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest hover:bg-slate-50 dark:hover:bg-slate-900 rounded-2xl transition-all order-2 sm:order-1 h-12 sm:h-14 flex items-center justify-center shrink-0"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl flex items-center justify-center gap-2 order-1 sm:order-2 h-12 sm:h-14 shrink-0"
                                >
                                    <CheckCircle className="w-4 h-4 shrink-0" />
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Create Account</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Banking;
