import React, { useState, useEffect } from 'react';
import { 
    Plus, Bank, Wallet, PencilSimple, Trash, CheckCircle, 
    XCircle, CurrencyDollar, Building
} from '@phosphor-icons/react';
import axios from 'axios';
import useAuthStore from '../store/authStore';

const fmt = v => `₦${Number(v || 0).toLocaleString()}`;

export default function BankAccounts() {
    const { user } = useAuthStore();
    const [accounts, setAccounts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [showTransferModal, setShowTransferModal] = useState(false);
    const [editingAccount, setEditingAccount] = useState(null);
    const [saving, setSaving] = useState(false);

    const [formData, setFormData] = useState({
        account_name: '',
        bank_name: '',
        account_number: '',
        account_type: 'current',
        currency: 'NGN',
        opening_balance: '',
        is_primary: false,
        notes: '',
    });

    const [transferForm, setTransferForm] = useState({
        from_account_id: '',
        to_account_id: '',
        amount: '',
        notes: '',
    });

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

    const fetchAccounts = async () => {
        try {
            setLoading(true);
            const res = await axios.get('/api/bank-accounts');
            setAccounts(res.data.data || []);
        } catch (error) {
            console.error('Error fetching bank accounts:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            if (editingAccount) {
                await axios.put(`/api/bank-accounts/${editingAccount.id}`, formData);
            } else {
                await axios.post('/api/bank-accounts', formData);
            }
            setShowModal(false);
            resetForm();
            fetchAccounts();
        } catch (error) {
            alert(error.response?.data?.message || 'Error saving bank account');
        } finally {
            setSaving(false);
        }
    };

    const handleEdit = (account) => {
        setEditingAccount(account);
        setFormData({
            account_name: account.account_name,
            bank_name: account.bank_name,
            account_number: account.account_number,
            account_type: account.account_type,
            currency: account.currency,
            opening_balance: account.opening_balance,
            is_primary: account.is_primary,
            notes: account.notes || '',
        });
        setShowModal(true);
    };

    const handleDelete = async (id) => {
        if (!confirm('Are you sure you want to delete this bank account?')) return;
        try {
            await axios.delete(`/api/bank-accounts/${id}`);
            fetchAccounts();
        } catch (error) {
            alert(error.response?.data?.message || 'Error deleting bank account');
        }
    };

    const handleTogglePrimary = async (account) => {
        try {
            await axios.put(`/api/bank-accounts/${account.id}`, { is_primary: !account.is_primary });
            fetchAccounts();
        } catch (error) {
            alert(error.response?.data?.message || 'Error updating primary account');
        }
    };

    const handleToggleActive = async (account) => {
        try {
            await axios.put(`/api/bank-accounts/${account.id}`, { is_active: !account.is_active });
            fetchAccounts();
        } catch (error) {
            alert(error.response?.data?.message || 'Error updating account status');
        }
    };

    const handleTransfer = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            await axios.post('/api/bank-accounts/transfer', transferForm);
            setShowTransferModal(false);
            setTransferForm({ from_account_id: '', to_account_id: '', amount: '', notes: '' });
            fetchAccounts();
            alert('Transfer completed successfully');
        } catch (error) {
            alert(error.response?.data?.message || 'Error transferring funds');
        } finally {
            setSaving(false);
        }
    };

    const resetForm = () => {
        setFormData({
            account_name: '',
            bank_name: '',
            account_number: '',
            account_type: 'current',
            currency: 'NGN',
            opening_balance: '',
            is_primary: false,
            notes: '',
        });
        setEditingAccount(null);
    };

    const openModal = () => {
        resetForm();
        setShowModal(true);
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 to-primary-50 p-6">
            {/* Header */}
            <div className="mb-8">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
                            <Bank size={36} weight="duotone" className="text-primary-600" />
                            Bank Accounts
                        </h1>
                        <p className="text-gray-600">Manage your company's bank accounts and track balances</p>
                    </div>
                    <div className="flex gap-2">
                        <button onClick={() => setShowTransferModal(true)}
                            className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-green-600 to-green-500 text-white rounded-xl hover:from-green-700 hover:to-green-600 transition-all shadow-lg">
                            <CurrencyDollar size={20} weight="bold" /> Transfer Funds
                        </button>
                        <button onClick={openModal}
                            className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-primary-600 to-primary-500 text-white rounded-xl hover:from-primary-700 hover:to-primary-600 transition-all shadow-lg">
                            <Plus size={20} weight="bold" /> Add Bank Account
                        </button>
                    </div>
                </div>
            </div>

            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div className="bg-gradient-to-br from-primary-500 to-primary-600 rounded-2xl shadow-xl p-6 text-white">
                    <div className="flex items-center justify-between mb-4">
                        <Wallet size={32} weight="duotone" className="opacity-80" />
                    </div>
                    <h3 className="text-sm font-medium opacity-90 mb-1">Total Balance</h3>
                    <p className="text-3xl font-bold">
                        {fmt(accounts.reduce((sum, a) => sum + Number(a.current_balance || 0), 0))}
                    </p>
                </div>

                <div className="bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-xl p-6 text-white">
                    <div className="flex items-center justify-between mb-4">
                        <CheckCircle size={32} weight="duotone" className="opacity-80" />
                    </div>
                    <h3 className="text-sm font-medium opacity-90 mb-1">Active Accounts</h3>
                    <p className="text-3xl font-bold">{accounts.filter(a => a.is_active).length}</p>
                </div>

                <div className="bg-gradient-to-br from-purple-500 to-purple-600 rounded-2xl shadow-xl p-6 text-white">
                    <div className="flex items-center justify-between mb-4">
                        <Building size={32} weight="duotone" className="opacity-80" />
                    </div>
                    <h3 className="text-sm font-medium opacity-90 mb-1">Total Accounts</h3>
                    <p className="text-3xl font-bold">{accounts.length}</p>
                </div>
            </div>

            {/* Accounts List */}
            {loading ? (
                <div className="flex items-center justify-center py-12">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
                </div>
            ) : accounts.length === 0 ? (
                <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-12 text-center">
                    <Bank size={64} className="mx-auto mb-4 text-gray-300" weight="duotone" />
                    <h3 className="text-xl font-semibold text-gray-700 mb-2">No Bank Accounts Yet</h3>
                    <p className="text-gray-500 mb-6">Add your first bank account to start tracking transactions</p>
                    <button onClick={openModal}
                        className="inline-flex items-center gap-2 px-6 py-3 bg-primary-600 text-white rounded-xl hover:bg-primary-700 transition-colors">
                        <Plus size={20} weight="bold" /> Add Bank Account
                    </button>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {accounts.map((account) => (
                        <div key={account.id} className={`bg-white rounded-2xl shadow-lg border p-6 hover:shadow-xl transition-all ${!account.is_active ? 'opacity-60' : ''}`}>
                            <div className="flex items-start justify-between mb-4">
                                <div className="flex items-center gap-3">
                                    <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-primary-500 to-primary-600 flex items-center justify-center text-white">
                                        <Bank size={24} weight="duotone" />
                                    </div>
                                    <div>
                                        <h3 className="font-bold text-lg text-gray-900">{account.account_name}</h3>
                                        <p className="text-sm text-gray-500">{account.bank_name}</p>
                                    </div>
                                </div>
                                <div className="flex gap-1">
                                    {account.is_primary && (
                                        <span className="px-2 py-1 bg-primary-100 text-primary-700 text-xs font-semibold rounded-full">Primary</span>
                                    )}
                                    {account.is_active ? (
                                        <span className="px-2 py-1 bg-green-100 text-green-700 text-xs font-semibold rounded-full">Active</span>
                                    ) : (
                                        <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs font-semibold rounded-full">Inactive</span>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-3 mb-4">
                                <div className="flex justify-between text-sm">
                                    <span className="text-gray-500">Account Number</span>
                                    <span className="font-mono font-semibold text-gray-900">{account.account_number}</span>
                                </div>
                                <div className="flex justify-between text-sm">
                                    <span className="text-gray-500">Type</span>
                                    <span className="font-semibold text-gray-900 capitalize">{account.account_type}</span>
                                </div>
                                <div className="flex justify-between text-sm">
                                    <span className="text-gray-500">Currency</span>
                                    <span className="font-semibold text-gray-900">{account.currency}</span>
                                </div>
                                <div className="flex justify-between text-sm bg-primary-50 rounded-lg p-3">
                                    <span className="text-primary-700 font-semibold">Current Balance</span>
                                    <span className="font-bold text-primary-900">{fmt(account.current_balance)}</span>
                                </div>
                            </div>

                            <div className="flex gap-2 pt-4 border-t border-gray-100">
                                <button onClick={() => handleEdit(account)}
                                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm font-semibold">
                                    <PencilSimple size={16} weight="bold" /> Edit
                                </button>
                                {!account.is_primary && (
                                    <button onClick={() => handleTogglePrimary(account)}
                                        className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-primary-100 text-primary-700 rounded-lg hover:bg-primary-200 transition-colors text-sm font-semibold">
                                        Make Primary
                                    </button>
                                )}
                                <button onClick={() => handleToggleActive(account)}
                                    className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg transition-colors text-sm font-semibold ${
                                        account.is_active 
                                            ? 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200' 
                                            : 'bg-green-100 text-green-700 hover:bg-green-200'
                                    }`}>
                                    {account.is_active ? 'Deactivate' : 'Activate'}
                                </button>
                                <button onClick={() => handleDelete(account.id)}
                                    className="px-3 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors text-sm font-semibold">
                                    <Trash size={16} weight="bold" />
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Add/Edit Modal */}
            {showModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => setShowModal(false)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
                        <div className="bg-gradient-to-r from-primary-600 to-primary-500 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
                            <div>
                                <h2 className="text-xl font-bold">{editingAccount ? 'Edit Bank Account' : 'Add Bank Account'}</h2>
                                <p className="text-xs opacity-80 mt-0.5">{editingAccount ? 'Update account details' : 'Add a new bank account'}</p>
                            </div>
                            <button onClick={() => setShowModal(false)} className="hover:bg-white/20 rounded-lg p-1">
                                <XCircle size={20} weight="bold" />
                            </button>
                        </div>
                        <form onSubmit={handleSubmit} className="p-6 space-y-4">
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Account Name *</label>
                                <input type="text" required value={formData.account_name}
                                    onChange={e => setFormData({...formData, account_name: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="e.g., Main Operating Account" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Bank Name *</label>
                                <input type="text" required value={formData.bank_name}
                                    onChange={e => setFormData({...formData, bank_name: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="e.g., First Bank" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Account Number *</label>
                                <input type="text" required value={formData.account_number}
                                    onChange={e => setFormData({...formData, account_number: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="e.g., 1234567890" />
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-semibold text-gray-700 mb-1">Account Type *</label>
                                    <select value={formData.account_type}
                                        onChange={e => setFormData({...formData, account_type: e.target.value})}
                                        className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white">
                                        <option value="current">Current</option>
                                        <option value="savings">Savings</option>
                                        <option value="domiciliary">Domiciliary</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-semibold text-gray-700 mb-1">Currency *</label>
                                    <select value={formData.currency}
                                        onChange={e => setFormData({...formData, currency: e.target.value})}
                                        className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white">
                                        <option value="NGN">NGN</option>
                                        <option value="USD">USD</option>
                                        <option value="EUR">EUR</option>
                                        <option value="GBP">GBP</option>
                                    </select>
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Opening Balance *</label>
                                <input type="number" required min="0" step="0.01" value={formData.opening_balance}
                                    onChange={e => setFormData({...formData, opening_balance: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="0.00" />
                            </div>
                            <div className="flex items-center gap-2">
                                <input type="checkbox" id="is_primary" checked={formData.is_primary}
                                    onChange={e => setFormData({...formData, is_primary: e.target.checked})}
                                    className="w-4 h-4 text-primary-600 rounded" />
                                <label htmlFor="is_primary" className="text-sm text-gray-700">Set as primary account</label>
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Notes</label>
                                <textarea value={formData.notes}
                                    onChange={e => setFormData({...formData, notes: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    rows={2} placeholder="Optional notes..." />
                            </div>
                            <div className="flex gap-3 pt-2">
                                <button type="button" onClick={() => setShowModal(false)}
                                    className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold hover:bg-gray-200 transition-colors">
                                    Cancel
                                </button>
                                <button type="submit" disabled={saving}
                                    className="flex-1 px-4 py-3 bg-gradient-to-r from-primary-600 to-primary-500 text-white rounded-xl font-semibold hover:from-primary-700 hover:to-primary-600 transition-colors disabled:opacity-50">
                                    {saving ? 'Saving...' : (editingAccount ? 'Update Account' : 'Add Account')}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* Transfer Modal */}
            {showTransferModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => setShowTransferModal(false)}>
                    <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
                        <div className="bg-gradient-to-r from-green-600 to-green-500 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
                            <div>
                                <h2 className="text-xl font-bold">Transfer Funds</h2>
                                <p className="text-xs opacity-80 mt-0.5">Move money between bank accounts</p>
                            </div>
                            <button onClick={() => setShowTransferModal(false)} className="hover:bg-white/20 rounded-lg p-1">
                                <XCircle size={20} weight="bold" />
                            </button>
                        </div>
                        <form onSubmit={handleTransfer} className="p-6 space-y-4">
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">From Account *</label>
                                <select required value={transferForm.from_account_id}
                                    onChange={e => setTransferForm({...transferForm, from_account_id: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent bg-white">
                                    <option value="">— Select source account —</option>
                                    {accounts.filter(a => a.is_active).map(account => (
                                        <option key={account.id} value={account.id}>
                                            {account.account_name} - {account.bank_name} ({fmt(account.current_balance)})
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">To Account *</label>
                                <select required value={transferForm.to_account_id}
                                    onChange={e => setTransferForm({...transferForm, to_account_id: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent bg-white">
                                    <option value="">— Select destination account —</option>
                                    {accounts.filter(a => a.is_active && a.id !== parseInt(transferForm.from_account_id)).map(account => (
                                        <option key={account.id} value={account.id}>
                                            {account.account_name} - {account.bank_name} ({fmt(account.current_balance)})
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Amount (NGN) *</label>
                                <input type="number" required min="0.01" step="0.01" value={transferForm.amount}
                                    onChange={e => setTransferForm({...transferForm, amount: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                                    placeholder="0.00" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 mb-1">Notes</label>
                                <textarea value={transferForm.notes}
                                    onChange={e => setTransferForm({...transferForm, notes: e.target.value})}
                                    className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                                    rows={2} placeholder="Optional notes..." />
                            </div>
                            <div className="flex gap-3 pt-2">
                                <button type="button" onClick={() => setShowTransferModal(false)}
                                    className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl font-semibold hover:bg-gray-200 transition-colors">
                                    Cancel
                                </button>
                                <button type="submit" disabled={saving}
                                    className="flex-1 px-4 py-3 bg-gradient-to-r from-green-600 to-green-500 text-white rounded-xl font-semibold hover:from-green-700 hover:to-green-600 transition-colors disabled:opacity-50">
                                    {saving ? 'Transferring...' : 'Transfer Funds'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
