import React, { useState, useMemo } from 'react';
import { 
  Building2, 
  Plus, 
  Search, 
  Filter, 
  Download,
  CreditCard,
  User,
  Users,
  X,
  Edit,
  Trash2,
  Copy,
  Check,
  AlertCircle,
  LayoutGrid,
  List,
  ChevronDown
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, BankDetail } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';

export default function BankDetails() {
  const { bankDetails, clients, engineers, projects, addBankDetail, updateBankDetail, deleteBankDetail, currencies, addCurrency } = useApp();
  const { hasPermission } = useAuth();
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState<'All' | 'Client' | 'Engineer' | 'Third-party'>('All');
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('table');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingDetail, setEditingDetail] = useState<BankDetail | null>(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [detailToDelete, setDetailToDelete] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [isAddingCurrency, setIsAddingCurrency] = useState(false);
  const [isManualEntity, setIsManualEntity] = useState(false);
  const [newCurrency, setNewCurrency] = useState({ code: '', symbol: '' });
  const [isCurrencyDropdownOpen, setIsCurrencyDropdownOpen] = useState(false);

  const [formData, setFormData] = useState<Partial<BankDetail>>({
    entityType: 'Client',
    entityId: '',
    bankName: '',
    accountName: '',
    accountNumber: '',
    iban: '',
    swiftCode: '',
    routingNumber: '',
    sortCode: '',
    institutionNumber: '',
    transitNumber: '',
    bankAddress: '',
    currency: 'USD'
  });

  const thirdParties = useMemo(() => {
    const names = new Set<string>();
    projects.forEach(p => {
      if (p.thirdPartyName) names.add(p.thirdPartyName);
      if (p.commissions) {
        p.commissions.forEach(c => names.add(c.vendorName));
      }
    });
    return Array.from(names).map(name => ({ id: name, name }));
  }, [projects]);

  const filteredDetails = useMemo(() => {
    return bankDetails.filter(detail => {
      const matchesSearch = 
        detail.entityName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        detail.bankName.toLowerCase().includes(searchQuery.toLowerCase()) ||
        detail.accountNumber.includes(searchQuery);
      
      const matchesType = filterType === 'All' || detail.entityType === filterType;
      
      return matchesSearch && matchesType;
    });
  }, [bankDetails, searchQuery, filterType]);

  const handleCopy = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    toast.success('Copied to clipboard');
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleSave = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.entityId || !formData.bankName || !formData.accountNumber) {
      toast.error('Please fill in all required fields');
      return;
    }

    let selectedEntityName = 'Unknown';
    if (formData.entityType === 'Client') {
      selectedEntityName = clients.find(c => c.id === formData.entityId)?.name || formData.entityId || 'Unknown';
    } else if (formData.entityType === 'Engineer') {
      selectedEntityName = engineers.find(e => e.id === formData.entityId)?.name || formData.entityId || 'Unknown';
    } else if (formData.entityType === 'Third-party') {
      selectedEntityName = formData.entityId || 'Unknown';
    }

    const detailData: BankDetail = {
      id: editingDetail?.id || `BNK-${Math.random().toString(36).substr(2, 5).toUpperCase()}`,
      entityId: formData.entityId,
      entityType: formData.entityType as any,
      entityName: selectedEntityName,
      bankName: formData.bankName,
      accountName: formData.accountName || '',
      accountNumber: formData.accountNumber,
      iban: formData.iban || '',
      swiftCode: formData.swiftCode || '',
      routingNumber: formData.routingNumber || '',
      sortCode: formData.sortCode || '',
      institutionNumber: formData.institutionNumber || '',
      transitNumber: formData.transitNumber || '',
      bankAddress: formData.bankAddress,
      currency: formData.currency || 'USD',
      createdAt: editingDetail?.createdAt || new Date().toISOString()
    };

    if (editingDetail) {
      updateBankDetail(editingDetail.id, detailData);
      toast.success('Bank details updated');
    } else {
      addBankDetail(detailData);
      toast.success('Bank details recorded');
    }

    setIsModalOpen(false);
    setEditingDetail(null);
    setIsAddingCurrency(false);
    setIsCurrencyDropdownOpen(false);
    setIsManualEntity(false);
    setNewCurrency({ code: '', symbol: '' });
    setFormData({
      entityType: 'Client',
      entityId: '',
      bankName: '',
      accountName: '',
      accountNumber: '',
      iban: '',
      swiftCode: '',
      routingNumber: '',
      sortCode: '',
      bankAddress: '',
      currency: 'USD'
    });
  };

  const handleDelete = () => {
    if (detailToDelete) {
      deleteBankDetail(detailToDelete);
      toast.success('Bank details deleted');
      setIsDeleteModalOpen(false);
      setDetailToDelete(null);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Bank Details</h1>
          <p className="text-muted-foreground">Manage banking information for clients and engineers.</p>
        </div>
        {hasPermission('finance.create') && (
          <button 
            onClick={() => setIsModalOpen(true)}
            className="flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all shadow-sm"
          >
            <Plus size={18} />
            Add Bank Details
          </button>
        )}
      </div>

      {/* Filters & Search */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center justify-between bg-card p-4 rounded-xl border border-border shadow-sm">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
          <input 
            type="text" 
            placeholder="Search by name, bank or account..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-10 pr-4 py-2 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
          />
        </div>
        
        <div className="flex items-center gap-2">
          <div className="flex rounded-lg border border-border p-1 bg-muted/50 mr-2">
            <button
              onClick={() => setViewMode('grid')}
              className={cn(
                "p-1.5 rounded-md transition-all",
                viewMode === 'grid' ? "bg-background text-primary shadow-sm" : "text-muted-foreground hover:text-foreground"
              )}
              title="Grid View"
            >
              <LayoutGrid size={16} />
            </button>
            <button
              onClick={() => setViewMode('table')}
              className={cn(
                "p-1.5 rounded-md transition-all",
                viewMode === 'table' ? "bg-background text-primary shadow-sm" : "text-muted-foreground hover:text-foreground"
              )}
              title="Table View"
            >
              <List size={16} />
            </button>
          </div>

          <div className="flex rounded-lg border border-border p-1 bg-muted/50">
            {(['All', 'Client', 'Engineer', 'Third-party'] as const).map((type) => (
              <button
                key={type}
                onClick={() => {
                  setFilterType(type);
                }}
                className={cn(
                  "px-3 py-1.5 text-xs font-bold rounded-md transition-all",
                  filterType === type 
                    ? "bg-background text-foreground shadow-sm" 
                    : "text-muted-foreground hover:text-foreground"
                )}
              >
                {type}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Bank Details Content */}
      {viewMode === 'grid' ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredDetails.map((detail) => (
          <div key={detail.id} className="group relative bg-card rounded-2xl border border-border p-6 shadow-sm hover:shadow-md transition-all">
            <div className="flex items-start justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className={cn(
                  "w-10 h-10 rounded-xl flex items-center justify-center",
                  detail.entityType === 'Client' ? "bg-blue-500/10 text-blue-500" : 
                  detail.entityType === 'Engineer' ? "bg-purple-500/10 text-purple-500" :
                  "bg-orange-500/10 text-orange-500"
                )}>
                  {detail.entityType === 'Client' ? <User size={20} /> : 
                   detail.entityType === 'Engineer' ? <Users size={20} /> : 
                   <Building2 size={20} />}
                </div>
                <div>
                  <h3 className="font-bold text-lg leading-none">{detail.entityName}</h3>
                  <p className="text-xs font-medium text-muted-foreground mt-1 uppercase tracking-wider">{detail.entityType}</p>
                </div>
              </div>
              <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                {hasPermission('finance.edit') && (
                  <button 
                    onClick={() => {
                      setEditingDetail(detail);
                      setFormData(detail);
                      setIsModalOpen(true);
                    }}
                    className="p-2 rounded-lg hover:bg-accent text-muted-foreground transition-colors"
                  >
                    <Edit size={16} />
                  </button>
                )}
                {hasPermission('finance.delete') && (
                  <button 
                    onClick={() => {
                      setDetailToDelete(detail.id);
                      setIsDeleteModalOpen(true);
                    }}
                    className="p-2 rounded-lg hover:bg-red-500/10 text-red-500 transition-colors"
                  >
                    <Trash2 size={16} />
                  </button>
                )}
              </div>
            </div>

            <div className="space-y-4">
              <div className="p-3 rounded-xl bg-muted/30 border border-border/50">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">Bank Name</span>
                </div>
                <p className="text-sm font-bold flex items-center gap-2">
                  <Building2 size={14} className="text-muted-foreground" />
                  {detail.bankName}
                </p>
                {detail.bankAddress && (
                  <p className="text-[10px] text-muted-foreground mt-1 line-clamp-2 italic">
                    {detail.bankAddress}
                  </p>
                )}
              </div>

              <div className="grid grid-cols-1 gap-3">
                {detail.iban && (
                  <div className="relative group/copy overflow-hidden">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block mb-1">IBAN</span>
                    <div className="flex items-center gap-2">
                      <code className="text-xs font-mono bg-muted/50 p-2 rounded-lg border border-border flex-1 truncate">
                        {detail.iban}
                      </code>
                      <button 
                        onClick={() => handleCopy(detail.iban, detail.id + '-iban')}
                        className="p-2 rounded-lg hover:bg-accent text-muted-foreground shrink-0 transition-colors"
                        title="Copy IBAN"
                      >
                        {copiedId === detail.id + '-iban' ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
                      </button>
                    </div>
                  </div>
                )}

                {detail.accountNumber && (
                  <div className="relative group/copy overflow-hidden">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block mb-1">Account Number</span>
                    <div className="flex items-center gap-2">
                      <code className="text-xs font-mono bg-muted/50 p-2 rounded-lg border border-border flex-1 truncate">
                        {detail.accountNumber}
                      </code>
                      <button 
                        onClick={() => handleCopy(detail.accountNumber, detail.id + '-acc')}
                        className="p-2 rounded-lg hover:bg-accent text-muted-foreground shrink-0 transition-colors"
                        title="Copy Account Number"
                      >
                        {copiedId === detail.id + '-acc' ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
                      </button>
                    </div>
                  </div>
                )}

                {(detail.swiftCode || detail.routingNumber || detail.sortCode) && (
                  <div className="grid grid-cols-2 gap-2 mt-1">
                    {detail.swiftCode && (
                      <div className="space-y-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block">SWIFT/BIC</span>
                        <code className="text-[10px] font-mono bg-muted/30 p-1.5 rounded border border-border block truncate">
                          {detail.swiftCode}
                        </code>
                      </div>
                    )}
                    {detail.routingNumber && (
                      <div className="space-y-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block">Routing #</span>
                        <code className="text-[10px] font-mono bg-muted/30 p-1.5 rounded border border-border block truncate">
                          {detail.routingNumber}
                        </code>
                      </div>
                    )}
                    {detail.institutionNumber && (
                      <div className="space-y-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block">Inst. #</span>
                        <code className="text-[10px] font-mono bg-muted/30 p-1.5 rounded border border-border block truncate">
                          {detail.institutionNumber}
                        </code>
                      </div>
                    )}
                    {detail.transitNumber && (
                      <div className="space-y-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block">Transit #</span>
                        <code className="text-[10px] font-mono bg-muted/30 p-1.5 rounded border border-border block truncate">
                          {detail.transitNumber}
                        </code>
                      </div>
                    )}
                    {detail.sortCode && (
                      <div className="space-y-1">
                        <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground block">Sort Code</span>
                        <code className="text-[10px] font-mono bg-muted/30 p-1.5 rounded border border-border block truncate">
                          {detail.sortCode}
                        </code>
                      </div>
                    )}
                  </div>
                )}
              </div>

              <div className="flex items-center justify-between pt-2 border-t border-border/50">
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <CreditCard size={12} />
                  <span>{detail.currency} Account</span>
                </div>
                <div className="text-xs text-muted-foreground font-mono">
                  {new Date(detail.createdAt).toLocaleDateString()}
                </div>
              </div>
            </div>
          </div>
        ))}

        {filteredDetails.length === 0 && (
          <div className="col-span-full py-12 flex flex-col items-center justify-center bg-card rounded-2xl border-2 border-dashed border-border text-center">
            <div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
              <Building2 size={32} className="text-muted-foreground opacity-20" />
            </div>
            <h3 className="text-lg font-bold">No bank details found</h3>
            <p className="text-muted-foreground max-w-xs mx-auto">
              Start by adding bank information for your clients or engineers.
            </p>
            <button 
              onClick={() => setIsModalOpen(true)}
              className="mt-6 flex items-center gap-2 text-primary font-bold hover:underline"
            >
              <Plus size={16} /> Record Bank Details
            </button>
          </div>
        )}
      </div>
      ) : (
        <div className="bg-card rounded-2xl border border-border shadow-sm overflow-hidden animate-in fade-in slide-in-from-bottom-2 duration-300">
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-border bg-muted/30">
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Entity</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Bank Name</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Account Info</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground">Identifiers</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground text-center">Currency</th>
                  <th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-muted-foreground text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border text-sm">
                {filteredDetails.map((detail) => (
                  <tr key={detail.id} className="hover:bg-muted/10 transition-colors group">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className={cn(
                          "w-8 h-8 rounded-lg flex items-center justify-center shrink-0",
                          detail.entityType === 'Client' ? "bg-blue-500/10 text-blue-500" : 
                          detail.entityType === 'Engineer' ? "bg-purple-500/10 text-purple-500" :
                          "bg-orange-500/10 text-orange-500"
                        )}>
                          {detail.entityType === 'Client' ? <User size={14} /> : 
                           detail.entityType === 'Engineer' ? <Users size={14} /> : 
                           <Building2 size={14} />}
                        </div>
                        <div>
                          <p className="font-bold">{detail.entityName}</p>
                          <p className="text-[10px] text-muted-foreground uppercase">{detail.entityType}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <p className="font-medium text-muted-foreground">{detail.bankName}</p>
                      {detail.bankAddress && (
                        <p className="text-[10px] text-muted-foreground italic mt-0.5 max-w-[150px] truncate" title={detail.bankAddress}>
                          {detail.bankAddress}
                        </p>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="space-y-1">
                        {detail.accountNumber && (
                          <div className="flex items-center gap-2 group/copy">
                            <span className="font-mono text-xs">{detail.accountNumber}</span>
                            <button onClick={() => handleCopy(detail.accountNumber, detail.id + '-acc')} className="opacity-0 group-hover/copy:opacity-100 transition-opacity p-1 hover:bg-muted rounded text-muted-foreground hover:text-primary">
                              <Copy size={12} />
                            </button>
                          </div>
                        )}
                        {detail.iban && (
                          <div className="flex items-center gap-2 group/copy">
                            <span className="font-mono text-[10px] text-muted-foreground">{detail.iban}</span>
                            <button onClick={() => handleCopy(detail.iban, detail.id + '-iban')} className="opacity-0 group-hover/copy:opacity-100 transition-opacity p-1 hover:bg-muted rounded text-muted-foreground hover:text-primary">
                              <Copy size={12} />
                            </button>
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-wrap gap-1.5">
                        {detail.swiftCode && <span className="text-[9px] bg-muted/50 px-1.5 py-0.5 rounded border border-border" title="SWIFT">SWIFT: {detail.swiftCode}</span>}
                        {detail.routingNumber && <span className="text-[9px] bg-muted/50 px-1.5 py-0.5 rounded border border-border" title="Routing">R: {detail.routingNumber}</span>}
                        {detail.institutionNumber && <span className="text-[9px] bg-muted/50 px-1.5 py-0.5 rounded border border-border" title="Institution">I: {detail.institutionNumber}</span>}
                        {detail.transitNumber && <span className="text-[9px] bg-muted/50 px-1.5 py-0.5 rounded border border-border" title="Transit">T: {detail.transitNumber}</span>}
                        {detail.sortCode && <span className="text-[9px] bg-muted/50 px-1.5 py-0.5 rounded border border-border" title="Sort Code">S: {detail.sortCode}</span>}
                      </div>
                    </td>
                    <td className="px-6 py-4 text-center">
                      <span className="text-[10px] font-bold px-2 py-0.5 bg-primary/10 text-primary rounded-full uppercase">
                        {detail.currency}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        {hasPermission('finance.edit') && (
                          <button 
                            onClick={() => {
                              setEditingDetail(detail);
                              setFormData(detail);
                              setIsModalOpen(true);
                            }}
                            className="p-1.5 rounded-lg hover:bg-accent text-muted-foreground transition-colors"
                          >
                            <Edit size={14} />
                          </button>
                        )}
                        {hasPermission('finance.delete') && (
                          <button 
                            onClick={() => {
                              setDetailToDelete(detail.id);
                              setIsDeleteModalOpen(true);
                            }}
                            className="p-1.5 rounded-lg hover:bg-red-500/10 text-red-500 transition-colors"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredDetails.length === 0 && (
                  <tr>
                    <td colSpan={6} className="px-6 py-12 text-center text-muted-foreground">
                      No bank details found matching your filters.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Record/Edit Bank Detail Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm overflow-y-auto">
          <div className="w-full max-w-2xl my-auto rounded-2xl border border-border bg-card p-0 shadow-2xl animate-in fade-in zoom-in duration-200 overflow-hidden">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-border bg-muted/30">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
                  <Building2 size={22} />
                </div>
                <div>
                  <h2 className="text-xl font-bold">{editingDetail ? 'Edit Bank Details' : 'Add Bank Details'}</h2>
                  <p className="text-xs text-muted-foreground">Enter specific banking information for settlements.</p>
                </div>
              </div>
              <button 
                onClick={() => {
                  setIsModalOpen(false);
                  setEditingDetail(null);
                  setIsAddingCurrency(false);
                  setIsManualEntity(false);
                  setNewCurrency({ code: '', symbol: '' });
                }}
                className="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors"
                type="button"
              >
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSave} className="p-6">
              <div className="space-y-8">
                {/* Section 1: Entity Information */}
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-4 flex items-center gap-2">
                    <User size={14} />
                    Beneficiary Information
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-sm font-semibold">Entity Type</label>
                      <div className="flex p-1 rounded-lg border border-border bg-muted/30">
                        {(['Client', 'Engineer', 'Third-party'] as const).map((type) => (
                          <button
                            key={type}
                            type="button"
                            onClick={() => setFormData({...formData, entityType: type, entityId: ''})}
                            className={cn(
                              "flex-1 py-1.5 text-xs font-bold rounded-md transition-all",
                              formData.entityType === type 
                                ? "bg-background text-primary shadow-sm" 
                                : "text-muted-foreground hover:text-foreground"
                            )}
                          >
                            {type}
                          </button>
                        ))}
                      </div>
                    </div>

                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-semibold">Select {formData.entityType} *</label>
                        <button 
                          type="button"
                          onClick={() => setIsManualEntity(!isManualEntity)}
                          className={cn(
                            "text-[10px] font-bold flex items-center gap-1 hover:underline",
                            isManualEntity ? "text-red-500" : "text-primary"
                          )}
                        >
                          {isManualEntity ? <List size={10} /> : <Plus size={10} />}
                          {isManualEntity ? "Switch to List" : "Add Manual Name"}
                        </button>
                      </div>
                      {isManualEntity ? (
                        <input 
                          type="text"
                          value={formData.entityId}
                          onChange={(e) => setFormData({...formData, entityId: e.target.value})}
                          placeholder={`Enter ${formData.entityType} Name`}
                          className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                          required
                        />
                      ) : (
                        <select 
                          value={formData.entityId}
                          onChange={(e) => setFormData({...formData, entityId: e.target.value})}
                          className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 appearance-none bg-[url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E')] bg-[length:16px] bg-[right:12px_center] bg-no-repeat pr-10"
                          required
                        >
                          <option value="">Choose from list...</option>
                          {formData.entityType === 'Client' ? (
                            clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)
                          ) : formData.entityType === 'Engineer' ? (
                            engineers.map(e => <option key={e.id} value={e.id}>{e.name}</option>)
                          ) : (
                            thirdParties.map(tp => <option key={tp.id} value={tp.id}>{tp.name}</option>)
                          )}
                        </select>
                      )}
                    </div>

                    <div className="md:col-span-2 space-y-2">
                      <label className="text-sm font-semibold">Account Beneficiary Name *</label>
                      <div className="relative">
                        <User className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                        <input 
                          type="text" 
                          value={formData.accountName || ''}
                          onChange={(e) => setFormData({...formData, accountName: e.target.value})}
                          placeholder="Full name or company name as it appears on bank records"
                          className="h-10 w-full pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                          required
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Section 2: Bank & Currency */}
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-4 flex items-center gap-2">
                    <Building2 size={14} />
                    Institution & Currency
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-semibold">Account Currency *</label>
                        <button 
                          type="button"
                          onClick={() => setIsAddingCurrency(!isAddingCurrency)}
                          className={cn(
                            "text-[10px] font-bold flex items-center gap-1 hover:underline",
                            isAddingCurrency ? "text-red-500" : "text-primary"
                          )}
                        >
                          {isAddingCurrency ? <X size={10} /> : <Plus size={10} />}
                          {isAddingCurrency ? "Cancel" : "Add Other"}
                        </button>
                      </div>
                      
                      {isAddingCurrency ? (
                        <div className="flex gap-2 animate-in slide-in-from-top-1 duration-200">
                          <input 
                            type="text" 
                            placeholder="e.g. JPY"
                            maxLength={3}
                            value={newCurrency.code}
                            onChange={(e) => setNewCurrency({...newCurrency, code: e.target.value.toUpperCase()})}
                            className="h-10 flex-1 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                          />
                          <button 
                            type="button"
                            onClick={() => {
                              if (newCurrency.code) {
                                if (!currencies.find(c => c.code === newCurrency.code)) {
                                  addCurrency(newCurrency.code, newCurrency.code);
                                  setFormData(prev => ({...prev, currency: newCurrency.code}));
                                  setIsAddingCurrency(false);
                                  setNewCurrency({ code: '', symbol: '' });
                                  toast.success(`Added ${newCurrency.code}`);
                                } else {
                                  toast.error('Exists');
                                }
                              }
                            }}
                            className="bg-primary text-primary-foreground px-3 py-2 rounded-lg text-xs font-bold"
                          >
                            Add
                          </button>
                        </div>
                      ) : (
                        <div className="grid grid-cols-5 gap-1.5 p-1 rounded-lg border border-border bg-muted/30">
                          {['USD', 'EUR', 'GBP', 'CAD'].map((curr) => (
                            <button
                              key={curr}
                              type="button"
                              onClick={() => setFormData({...formData, currency: curr})}
                              className={cn(
                                "py-1.5 text-xs font-bold rounded-md transition-all",
                                formData.currency === curr 
                                  ? "bg-background text-primary shadow-sm border border-primary/20" 
                                  : "text-muted-foreground hover:text-foreground"
                              )}
                            >
                              {curr}
                            </button>
                          ))}
                          <div className="relative group">
                            <button
                              type="button"
                              onClick={() => setIsCurrencyDropdownOpen(!isCurrencyDropdownOpen)}
                              className={cn(
                                "w-full py-1.5 text-xs font-bold rounded-md transition-all flex items-center justify-center gap-1",
                                !['USD', 'EUR', 'GBP', 'CAD'].includes(formData.currency || '')
                                  ? "bg-background text-primary shadow-sm border border-primary/20" 
                                  : "text-muted-foreground hover:text-foreground"
                              )}
                            >
                              {['USD', 'EUR', 'GBP', 'CAD'].includes(formData.currency || '') ? 'More' : formData.currency}
                              <ChevronDown size={12} className={cn("transition-transform", isCurrencyDropdownOpen && "rotate-180")} />
                            </button>
                            {isCurrencyDropdownOpen && (
                              <div className="absolute top-full left-0 right-0 z-50 mt-1 max-h-40 overflow-auto rounded-lg border border-border bg-popover p-1 shadow-lg backdrop-blur-sm animate-in fade-in zoom-in-95 duration-200">
                                {currencies.filter(c => !['USD', 'EUR', 'GBP', 'CAD'].includes(c.code)).map(curr => (
                                  <button
                                    key={curr.code}
                                    type="button"
                                    onClick={() => {
                                      setFormData({...formData, currency: curr.code});
                                      setIsCurrencyDropdownOpen(false);
                                    }}
                                    className={cn(
                                      "flex w-full items-center justify-between rounded-md px-2 py-1.5 text-xs transition-colors hover:bg-accent",
                                      formData.currency === curr.code ? "bg-accent text-primary font-bold" : "text-popover-foreground"
                                    )}
                                  >
                                    {curr.code}
                                    {formData.currency === curr.code && <Check size={12} />}
                                  </button>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="space-y-2">
                      <label className="text-sm font-semibold">Bank Name *</label>
                      <div className="relative">
                        <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />
                        <input 
                          type="text" 
                          value={formData.bankName || ''}
                          onChange={(e) => setFormData({...formData, bankName: e.target.value})}
                          placeholder="e.g. HSBC, Emirates NBD, Chase"
                          className="h-10 w-full pl-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                          required
                        />
                      </div>
                    </div>

                    <div className="md:col-span-2 space-y-2">
                      <label className="text-sm font-semibold text-muted-foreground">Bank Branch Address (Optional)</label>
                      <textarea 
                        value={formData.bankAddress || ''}
                        onChange={(e) => setFormData({...formData, bankAddress: e.target.value})}
                        placeholder="Full physical address of the bank branch for international wire transfers"
                        className="w-full rounded-lg border border-border bg-background p-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 min-h-[70px] resize-none"
                      />
                    </div>
                  </div>
                </div>

                {/* Section 3: Account Details (Dynamic) */}
                <div className="pt-4 border-t border-border">
                  <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-4 flex items-center gap-2">
                    <CreditCard size={14} />
                    Account Specifications ({formData.currency})
                  </h3>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6 bg-muted/20 p-6 rounded-2xl border border-border/50">
                    {/* USD Specific Fields */}
                    {formData.currency === 'USD' && (
                      <>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">Account Number *</label>
                          <input 
                            type="text" 
                            value={formData.accountNumber || ''}
                            onChange={(e) => setFormData({...formData, accountNumber: e.target.value})}
                            placeholder="USA Checking/Savings Account #"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">ABA Routing Number</label>
                          <input 
                            type="text" 
                            value={formData.routingNumber || ''}
                            onChange={(e) => setFormData({...formData, routingNumber: e.target.value})}
                            placeholder="9-digit ACH/Wire Routing #"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">SWIFT/BIC Code</label>
                          <input 
                            type="text" 
                            value={formData.swiftCode || ''}
                            onChange={(e) => setFormData({...formData, swiftCode: e.target.value})}
                            placeholder="SWIFT Code for international wire"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                          />
                        </div>
                      </>
                    )}

                    {/* EUR Specific Fields */}
                    {formData.currency === 'EUR' && (
                      <>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold">IBAN *</label>
                          <input 
                            type="text" 
                            value={formData.iban || ''}
                            onChange={(e) => setFormData({...formData, iban: e.target.value})}
                            placeholder="International Bank Account Number"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold">BIC / SWIFT *</label>
                          <input 
                            type="text" 
                            value={formData.swiftCode || ''}
                            onChange={(e) => setFormData({...formData, swiftCode: e.target.value})}
                            placeholder="Bank Identifier Code"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required={formData.currency === 'EUR'}
                          />
                        </div>
                      </>
                    )}

                    {/* GBP Specific Fields */}
                    {formData.currency === 'GBP' && (
                      <>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">Account Number *</label>
                          <input 
                            type="text" 
                            value={formData.accountNumber || ''}
                            onChange={(e) => setFormData({...formData, accountNumber: e.target.value})}
                            placeholder="8-digit UK Account Number"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">Sort Code *</label>
                          <input 
                            type="text" 
                            value={formData.sortCode || ''}
                            onChange={(e) => setFormData({...formData, sortCode: e.target.value})}
                            placeholder="XX-XX-XX"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required={formData.currency === 'GBP'}
                          />
                        </div>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold italic text-muted-foreground">Note: For GBP, Account Number and Sort Code are mandatory identifiers.</label>
                        </div>
                      </>
                    )}

                    {/* CAD Specific Fields */}
                    {formData.currency === 'CAD' && (
                      <>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold">Account Number *</label>
                          <input 
                            type="text" 
                            value={formData.accountNumber || ''}
                            onChange={(e) => setFormData({...formData, accountNumber: e.target.value})}
                            placeholder="Canadian Bank Account Number"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">Transit Number *</label>
                          <input 
                            type="text" 
                            value={formData.transitNumber || ''}
                            onChange={(e) => setFormData({...formData, transitNumber: e.target.value})}
                            placeholder="5-digit Transit #"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required={formData.currency === 'CAD'}
                          />
                          <p className="text-[10px] text-muted-foreground">Identifies the specific branch.</p>
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">Institution Number *</label>
                          <input 
                            type="text" 
                            value={formData.institutionNumber || ''}
                            onChange={(e) => setFormData({...formData, institutionNumber: e.target.value})}
                            placeholder="3-digit Bank Code"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required={formData.currency === 'CAD'}
                          />
                          <p className="text-[10px] text-muted-foreground">Identifies the financial institution.</p>
                        </div>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold">SWIFT Code</label>
                          <input 
                            type="text" 
                            value={formData.swiftCode || ''}
                            onChange={(e) => setFormData({...formData, swiftCode: e.target.value})}
                            placeholder="For international wires to Canada"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                          />
                        </div>
                      </>
                    )}

                    {/* Other Currencies Fallback */}
                    {!['USD', 'EUR', 'GBP', 'CAD'].includes(formData.currency || '') && (
                      <>
                        <div className="space-y-2 md:col-span-2">
                          <label className="text-sm font-semibold">Account Number *</label>
                          <input 
                            type="text" 
                            value={formData.accountNumber || ''}
                            onChange={(e) => setFormData({...formData, accountNumber: e.target.value})}
                            placeholder="International Account Number"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">IBAN (if applicable)</label>
                          <input 
                            type="text" 
                            value={formData.iban || ''}
                            onChange={(e) => setFormData({...formData, iban: e.target.value})}
                            placeholder="International Format"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                          />
                        </div>
                        <div className="space-y-2">
                          <label className="text-sm font-semibold">SWIFT / BIC *</label>
                          <input 
                            type="text" 
                            value={formData.swiftCode || ''}
                            onChange={(e) => setFormData({...formData, swiftCode: e.target.value})}
                            placeholder="Global Bank Identifier"
                            className="h-10 w-full rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                            required
                          />
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="mt-8 flex items-center gap-3">
                <button 
                  type="button"
                  onClick={() => {
                    setIsModalOpen(false);
                    setEditingDetail(null);
                    setIsAddingCurrency(false);
                    setIsCurrencyDropdownOpen(false);
                    setNewCurrency({ code: '', symbol: '' });
                  }}
                  className="flex-1 h-11 text-sm font-bold border border-border rounded-xl hover:bg-accent transition-all"
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="flex-[2] bg-primary h-11 text-sm font-bold text-primary-foreground rounded-xl hover:bg-primary/90 transition-all shadow-lg active:scale-[0.98]"
                >
                  {editingDetail ? 'Update Bank Record' : 'Create Bank Record'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-sm rounded-xl border border-border bg-card p-6 shadow-2xl">
            <div className="flex items-center gap-3 text-red-500 mb-4">
              <AlertCircle size={24} />
              <h2 className="text-lg font-bold">Delete Bank Details?</h2>
            </div>
            <p className="text-sm text-muted-foreground mb-6">
              This action cannot be undone. This will permanently delete the bank information from the system.
            </p>
            <div className="flex gap-3">
              <button 
                onClick={() => setIsDeleteModalOpen(false)}
                className="flex-1 px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-accent transition-colors"
              >
                Cancel
              </button>
              <button 
                onClick={handleDelete}
                className="flex-1 bg-red-500 px-4 py-2 text-sm font-bold text-white rounded-lg hover:bg-red-600 transition-colors shadow-sm"
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
