'use client';

import { useState, useEffect, useRef } from 'react';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface BankAccountData {
  id: number;
  bank_name: string;
  account_title: string;
  account_number: string;
  iban: string | null;
  branch_code: string | null;
  swift_code: string | null;
  is_active: boolean;
  sort_order: number;
}

interface BankAccountFormModalProps {
  isOpen: boolean;
  // null = create a new bank account; a row = edit that one
  account: BankAccountData | null;
  onClose: () => void;
  onSaved: () => void;
}

const EMPTY_FORM = {
  bank_name: '',
  account_title: '',
  account_number: '',
  iban: '',
  branch_code: '',
  swift_code: '',
  is_active: true,
  sort_order: 0,
};

export default function BankAccountFormModal({ isOpen, account, onClose, onSaved }: BankAccountFormModalProps) {
  const [form, setForm] = useState(EMPTY_FORM);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const prevIdRef = useRef<number | null>(null);

  useEffect(() => {
    if (!isOpen) {
      prevIdRef.current = null;
      return;
    }
    const currentId = account?.id ?? null;
    if (currentId === prevIdRef.current) return;
    prevIdRef.current = currentId;

    setForm(
      account
        ? {
            bank_name: account.bank_name,
            account_title: account.account_title,
            account_number: account.account_number,
            iban: account.iban ?? '',
            branch_code: account.branch_code ?? '',
            swift_code: account.swift_code ?? '',
            is_active: account.is_active,
            sort_order: account.sort_order,
          }
        : EMPTY_FORM,
    );
    setErrors({});
  }, [isOpen, account]);

  const handleSubmit = async () => {
    const newErrors: Record<string, string> = {};
    if (form.bank_name.trim().length < 2) newErrors.bank_name = 'Bank name is required';
    if (form.account_title.trim().length < 2) newErrors.account_title = 'Account title is required';
    if (form.account_number.trim().length < 4) newErrors.account_number = 'Account number is required';
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    try {
      const payload = {
        bank_name: form.bank_name.trim(),
        account_title: form.account_title.trim(),
        account_number: form.account_number.trim(),
        iban: form.iban.trim() || null,
        branch_code: form.branch_code.trim() || null,
        swift_code: form.swift_code.trim() || null,
        is_active: form.is_active,
        sort_order: form.sort_order,
      };

      const res = await fetch(account ? `/api/bank-accounts/${account.id}` : '/api/bank-accounts', {
        method: account ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        toast.success(account ? 'Bank account updated' : 'Bank account created');
        onSaved();
        onClose();
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, account ? 'Failed to update bank account' : 'Failed to create bank account'));
      }
    } catch {
      toast.error('Network error');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  const inputStyle = (hasError: boolean) => ({
    background: 'var(--color-surface-alt)',
    border: hasError ? '1px solid var(--color-danger)' : '1px solid var(--color-border)',
    color: 'var(--color-text)',
  });

  return (
    <div className="fixed inset-0 z-60 flex items-center justify-center p-4" style={{ background: 'rgba(0,0,0,0.5)' }}>
      <div className="rounded-lg p-6 w-full max-w-lg max-h-[90vh] overflow-y-auto" style={{
        background: 'var(--color-surface)', border: '1px solid var(--color-border)', boxShadow: 'var(--shadow-card-lg)',
      }}>
        <h3 className="text-lg font-semibold mb-4" style={{ color: 'var(--color-text)' }}>
          {account ? 'Edit Bank Account' : 'Add Bank Account'}
        </h3>

        <div className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">Bank Name <span className="text-red-500">*</span></label>
              <input type="text" value={form.bank_name}
                onChange={(e) => { setForm((p) => ({ ...p, bank_name: e.target.value })); setErrors((p) => ({ ...p, bank_name: '' })); }}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(!!errors.bank_name)} />
              {errors.bank_name && <p className="text-xs mt-1 text-red-500">{errors.bank_name}</p>}
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Account Title <span className="text-red-500">*</span></label>
              <input type="text" value={form.account_title}
                onChange={(e) => { setForm((p) => ({ ...p, account_title: e.target.value })); setErrors((p) => ({ ...p, account_title: '' })); }}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(!!errors.account_title)} />
              {errors.account_title && <p className="text-xs mt-1 text-red-500">{errors.account_title}</p>}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Account Number <span className="text-red-500">*</span></label>
            <input type="text" value={form.account_number}
              onChange={(e) => { setForm((p) => ({ ...p, account_number: e.target.value })); setErrors((p) => ({ ...p, account_number: '' })); }}
              className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(!!errors.account_number)} />
            {errors.account_number && <p className="text-xs mt-1 text-red-500">{errors.account_number}</p>}
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">IBAN</label>
              <input type="text" value={form.iban}
                onChange={(e) => setForm((p) => ({ ...p, iban: e.target.value }))}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(false)} />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Branch Code</label>
              <input type="text" value={form.branch_code}
                onChange={(e) => setForm((p) => ({ ...p, branch_code: e.target.value }))}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(false)} />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">SWIFT Code</label>
              <input type="text" value={form.swift_code}
                onChange={(e) => setForm((p) => ({ ...p, swift_code: e.target.value }))}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(false)} />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 items-end">
            <div>
              <label className="block text-sm font-medium mb-1">Sort Order</label>
              <input type="number" min={0} value={form.sort_order}
                onChange={(e) => setForm((p) => ({ ...p, sort_order: Number(e.target.value) || 0 }))}
                className="w-full px-3 py-2 rounded-lg text-sm" style={inputStyle(false)} />
            </div>
            <label className="flex items-center gap-2 pb-2 cursor-pointer">
              <input type="checkbox" checked={form.is_active}
                onChange={(e) => setForm((p) => ({ ...p, is_active: e.target.checked }))} />
              <span className="text-sm font-medium">Active</span>
            </label>
          </div>
        </div>

        <div className="flex gap-3 justify-end mt-6">
          <button onClick={onClose} className="px-4 py-2 rounded-lg text-sm"
            style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text)', border: '1px solid var(--color-border)' }}>Cancel</button>
          <button onClick={handleSubmit} disabled={loading}
            className="px-4 py-2 rounded-lg text-sm text-white disabled:opacity-50"
            style={{ background: 'var(--color-cta)' }}>{loading ? 'Saving...' : 'Save'}</button>
        </div>
      </div>
    </div>
  );
}
