import React, { useState, useEffect } from "react";
import axios from "axios";
import { toast } from "react-hot-toast";
import {
  Bank,
  Plus,
  PencilSimple,
  Trash,
  Check,
  X,
} from "@phosphor-icons/react";

const SuperAdminBankAccounts = () => {
  const [accounts, setAccounts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingAccount, setEditingAccount] = useState(null);
  const [formData, setFormData] = useState({
    bank_name: "",
    account_number: "",
    account_name: "",
    account_type: "current",
    currency: "NGN",
    opening_balance: 0,
    is_primary: false,
    is_active: true,
    notes: "",
  });

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

  const loadAccounts = async () => {
    setLoading(true);
    try {
      const res = await axios.get("/api/super-admin-bank-accounts");
      setAccounts(res.data.data || []);
    } catch (e) {
      toast.error("Failed to load bank accounts");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingAccount) {
        await axios.put(
          `/api/super-admin-bank-accounts/${editingAccount.id}`,
          formData,
        );
        toast.success("Bank account updated");
      } else {
        await axios.post("/api/super-admin-bank-accounts", formData);
        toast.success("Bank account created");
      }
      setShowModal(false);
      setEditingAccount(null);
      setFormData({
        bank_name: "",
        account_number: "",
        account_name: "",
        account_type: "checking",
        currency: "NGN",
        current_balance: 0,
        is_primary: false,
        is_active: true,
      });
      loadAccounts();
    } catch (e) {
      toast.error(e.response?.data?.message || "Failed to save bank account");
    }
  };

  const handleEdit = (account) => {
    setEditingAccount(account);
    setFormData({
      bank_name: account.bank_name,
      account_number: account.account_number,
      account_name: account.account_name,
      account_type: account.account_type,
      currency: account.currency,
      opening_balance: account.opening_balance,
      is_primary: account.is_primary,
      is_active: account.is_active,
      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/super-admin-bank-accounts/${id}`);
      toast.success("Bank account deleted");
      loadAccounts();
    } catch (e) {
      toast.error("Failed to delete bank account");
    }
  };

  const handleSetPrimary = async (id) => {
    try {
      await axios.post(`/api/super-admin-bank-accounts/${id}/set-primary`);
      toast.success("Primary account updated");
      loadAccounts();
    } catch (e) {
      toast.error("Failed to set primary account");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            Super Admin Bank Accounts
          </h1>
          <p className="text-gray-500">Manage bank accounts for Super Admin</p>
        </div>
        <button
          onClick={() => {
            setEditingAccount(null);
            setFormData({
              bank_name: "",
              account_number: "",
              account_name: "",
              account_type: "current",
              currency: "NGN",
              opening_balance: 0,
              is_primary: false,
              is_active: true,
              notes: "",
            });
            setShowModal(true);
          }}
          className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
        >
          <Plus size={20} />
          Add Bank Account
        </button>
      </div>

      {/* Accounts List */}
      {accounts.length === 0 ? (
        <div className="bg-white rounded-xl p-12 text-center border border-gray-100">
          <Bank size={48} className="text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            No Bank Accounts
          </h3>
          <p className="text-gray-500 mb-4">
            Add your first bank account to get started
          </p>
          <button
            onClick={() => {
              setEditingAccount(null);
              setFormData({
                bank_name: "",
                account_number: "",
                account_name: "",
                account_type: "current",
                currency: "NGN",
                opening_balance: 0,
                is_primary: false,
                is_active: true,
                notes: "",
              });
              setShowModal(true);
            }}
            className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
          >
            Add Bank Account
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {accounts.map((account) => (
            <div
              key={account.id}
              className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="w-12 h-12 rounded-lg bg-primary-100 flex items-center justify-center">
                  <Bank size={24} className="text-primary-600" />
                </div>
                <div className="flex items-center gap-2">
                  {account.is_primary && (
                    <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-md">
                      Primary
                    </span>
                  )}
                  {!account.is_active && (
                    <span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-md">
                      Inactive
                    </span>
                  )}
                </div>
              </div>
              <h3 className="font-semibold text-gray-900 mb-1">
                {account.bank_name}
              </h3>
              <p className="text-sm text-gray-500 mb-1">
                {account.account_number}
              </p>
              <p className="text-sm text-gray-500 mb-4">
                {account.account_name}
              </p>
              <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                <div>
                  <p className="text-xs text-gray-500">Balance</p>
                  <p className="font-semibold text-gray-900">
                    ₦{Number(account.current_balance).toLocaleString()}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  {!account.is_primary && (
                    <button
                      onClick={() => handleSetPrimary(account.id)}
                      className="p-2 text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                      title="Set as primary"
                    >
                      <Check size={18} />
                    </button>
                  )}
                  <button
                    onClick={() => handleEdit(account)}
                    className="p-2 text-primary-600 hover:bg-primary-50 rounded-lg transition-colors"
                    title="Edit"
                  >
                    <PencilSimple size={18} />
                  </button>
                  <button
                    onClick={() => handleDelete(account.id)}
                    className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                    title="Delete"
                  >
                    <Trash size={18} />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <div
          className="fixed inset-0 bg-black bg-opacity-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-md"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="bg-gradient-to-r from-primary-600 to-primary-700 text-white px-6 py-4 rounded-t-2xl flex justify-between items-center">
              <h2 className="text-xl font-bold">
                {editingAccount ? "Edit Bank Account" : "Add Bank Account"}
              </h2>
              <button
                onClick={() => setShowModal(false)}
                className="hover:bg-white/20 rounded-lg p-1"
              >
                <X size={20} weight="bold" />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium 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-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="e.g., Access Bank"
                />
              </div>
              <div>
                <label className="block text-sm font-medium 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-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="e.g., 1234567890"
                />
              </div>
              <div>
                <label className="block text-sm font-medium 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-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="e.g., Sarkin Mota Group"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium 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-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  >
                    <option value="current">Current</option>
                    <option value="savings">Savings</option>
                    <option value="domiciliary">Domiciliary</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Currency
                  </label>
                  <select
                    value={formData.currency}
                    onChange={(e) =>
                      setFormData({ ...formData, currency: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  >
                    <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-medium text-gray-700 mb-1">
                  Opening Balance *
                </label>
                <input
                  type="number"
                  step="0.01"
                  required
                  value={formData.opening_balance}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      opening_balance: parseFloat(e.target.value) || 0,
                    })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="0.00"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Notes
                </label>
                <textarea
                  value={formData.notes}
                  onChange={(e) =>
                    setFormData({ ...formData, notes: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
                  placeholder="Optional notes..."
                  rows="2"
                />
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.is_primary}
                    onChange={(e) =>
                      setFormData({ ...formData, is_primary: e.target.checked })
                    }
                    className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">
                    Set as primary account
                  </span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.is_active}
                    onChange={(e) =>
                      setFormData({ ...formData, is_active: e.target.checked })
                    }
                    className="w-4 h-4 text-primary-600 rounded focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">Active</span>
                </label>
              </div>
              <div className="flex gap-3 pt-4">
                <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"
                  className="flex-1 px-4 py-3 bg-primary-600 text-white rounded-xl font-semibold hover:bg-primary-700 transition-colors"
                >
                  {editingAccount ? "Update" : "Create"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default SuperAdminBankAccounts;
