// QuickBookModal - Modal for simple one-account booking

import { useState, useEffect, useMemo, useRef } from 'react';
import {
  Modal,
  Form,
  Input,
  Card,
  Table,
  Typography,
  Alert,
  Divider,
  Tag,
} from 'antd';
import { CheckCircleOutlined, WarningOutlined } from '@ant-design/icons';
import { formatCurrency, formatDateShort } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import { generateSimpleDoubleEntry, type SimpleBookingInput } from '@/lib/accounting';
import type { VATCode } from '@/types/vat';
import type { Account } from '@/types/accounting';
import { AccountQuickPicker, VATCodePicker } from './AccountQuickPicker';
import {
  useBookingPreview,
  useIsBookingSaving,
  useSimpleBookingStore,
} from '@/stores/simpleBookingStore';

const { Text } = Typography;

interface QuickBookModalProps {
  accounts: Account[];
  onSubmit: (transaction: ReturnType<typeof generateSimpleDoubleEntry>) => Promise<void>;
}

export function QuickBookModal({ accounts, onSubmit }: QuickBookModalProps) {
  const { modal, closeModal, setPreview } = useSimpleBookingStore();
  const preview = useBookingPreview();
  const isSaving = useIsBookingSaving();

  const [selectedAccountId, setSelectedAccountId] = useState<string | undefined>();
  const [selectedVATCode, setSelectedVATCode] = useState<VATCode>('K25');
  const [description, setDescription] = useState('');

  const bankTransaction = modal.bankTransaction;
  const isOpen = modal.isOpen && modal.type === 'simple';
  const isExpense = bankTransaction ? bankTransaction.amount < 0 : true;

  // Track previous open state to detect modal opening
  const wasOpenRef = useRef(false);
  const lastTransactionIdRef = useRef<string | null>(null);

  // Reset form only when modal opens or transaction changes
  useEffect(() => {
    const isNewlyOpened = isOpen && !wasOpenRef.current;
    const isNewTransaction = bankTransaction && bankTransaction.id !== lastTransactionIdRef.current;

    if (isOpen && bankTransaction && (isNewlyOpened || isNewTransaction)) {
      // Calculate isExpense inside effect to avoid dependency
      const expense = bankTransaction.amount < 0;
      setSelectedAccountId(undefined);
      setSelectedVATCode(expense ? 'K25' : 'S25');
      setDescription(bankTransaction.description);
      setPreview(null);
      lastTransactionIdRef.current = bankTransaction.id;
    }

    wasOpenRef.current = isOpen;
  }, [isOpen, bankTransaction, setPreview]);

  // Generate preview when inputs change
  useEffect(() => {
    if (!bankTransaction || !selectedAccountId) {
      setPreview(null);
      return;
    }

    const account = accounts.find((a) => a.id === selectedAccountId);
    if (!account) {
      setPreview(null);
      return;
    }

    const input: SimpleBookingInput = {
      bankTransaction: {
        id: bankTransaction.id,
        date: bankTransaction.date,
        amount: bankTransaction.amount,
        description: description || bankTransaction.description,
        counterparty: bankTransaction.counterparty,
        bankAccountId: bankTransaction.bankAccountId,
        bankAccountNumber: bankTransaction.bankAccountNumber,
      },
      contraAccountId: account.id,
      contraAccountNumber: account.accountNumber,
      contraAccountName: account.name,
      vatCode: selectedVATCode,
      description: description || undefined,
    };

    const result = generateSimpleDoubleEntry(input);
    setPreview(result);
  }, [bankTransaction, selectedAccountId, selectedVATCode, description, accounts, setPreview]);

  // Account options for picker
  const accountOptions = useMemo(
    () =>
      accounts.map((a) => ({
        id: a.id,
        accountNumber: a.accountNumber,
        name: a.name,
        type: a.type,
      })),
    [accounts]
  );

  const handleAccountChange = (accountId: string) => {
    setSelectedAccountId(accountId);
  };

  const handleSubmit = async () => {
    if (!preview || !preview.isValid) return;
    await onSubmit(preview);
    closeModal();
  };

  const previewColumns = [
    {
      title: 'Konto',
      key: 'account',
      render: (_: unknown, record: { accountNumber: string; accountName: string }) => (
        <span>
          <Text strong>{record.accountNumber}</Text>
          <Text style={{ marginLeft: 8 }}>{record.accountName}</Text>
        </span>
      ),
    },
    {
      title: 'Debet',
      dataIndex: 'debit',
      key: 'debit',
      align: 'right' as const,
      render: (value: number) =>
        value > 0 ? (
          <Text style={{ color: accountingColors.debit }}>{formatCurrency(value)}</Text>
        ) : null,
    },
    {
      title: 'Kredit',
      dataIndex: 'credit',
      key: 'credit',
      align: 'right' as const,
      render: (value: number) =>
        value > 0 ? (
          <Text style={{ color: accountingColors.credit }}>{formatCurrency(value)}</Text>
        ) : null,
    },
  ];

  if (!bankTransaction) return null;

  return (
    <Modal
      title="Bogfoer transaktion"
      open={isOpen}
      onCancel={closeModal}
      onOk={handleSubmit}
      okText="Bogfoer"
      cancelText="Annuller"
      okButtonProps={{
        disabled: !preview?.isValid || isSaving,
        loading: isSaving,
      }}
      width={600}
      destroyOnClose
    >
      {/* Bank transaction summary */}
      <Card
        size="small"
        style={{
          marginBottom: 16,
          borderLeft: `3px solid ${isExpense ? accountingColors.debit : accountingColors.credit}`,
        }}
      >
        <div>
          <Text
            strong
            style={{
              fontSize: 18,
              color: isExpense ? accountingColors.debit : accountingColors.credit,
            }}
          >
            {formatCurrency(bankTransaction.amount)}
          </Text>
        </div>
        <Text>{bankTransaction.description}</Text>
        <div style={{ marginTop: 4 }}>
          <Text type="secondary">{formatDateShort(bankTransaction.date)}</Text>
          {bankTransaction.counterparty && (
            <>
              <Text type="secondary"> • </Text>
              <Text type="secondary">{bankTransaction.counterparty}</Text>
            </>
          )}
        </div>
      </Card>

      {/* Account selection */}
      <Form layout="vertical">
        <Form.Item label="Vaelg konto" required>
          <AccountQuickPicker
            accounts={accountOptions}
            value={selectedAccountId}
            onChange={handleAccountChange}
            isExpense={isExpense}
            placeholder="Soeg efter konto..."
          />
        </Form.Item>

        <Form.Item label="Momskode" required>
          <VATCodePicker
            value={selectedVATCode}
            onChange={setSelectedVATCode}
            isExpense={isExpense}
            showDescription
          />
        </Form.Item>

        <Form.Item label="Beskrivelse (valgfri)">
          <Input
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder={bankTransaction.description}
          />
        </Form.Item>
      </Form>

      {/* Preview */}
      {preview && (
        <>
          <Divider style={{ margin: '16px 0' }} />
          <div>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <Text strong style={{ marginRight: 8 }}>Forhaandsvisning:</Text>
              {preview.isValid ? (
                <Tag color="success" icon={<CheckCircleOutlined />}>
                  Balancerer
                </Tag>
              ) : (
                <Tag color="error" icon={<WarningOutlined />}>
                  Fejl
                </Tag>
              )}
            </div>

            {!preview.isValid && preview.validationMessage && (
              <Alert
                type="error"
                message={preview.validationMessage}
                style={{ marginBottom: 8 }}
              />
            )}

            <Table
              dataSource={preview.lines.map((line, idx) => ({ ...line, key: idx }))}
              columns={previewColumns}
              pagination={false}
              size="small"
              bordered
              summary={() => {
                const totalDebit = preview.lines.reduce((sum, l) => sum + l.debit, 0);
                const totalCredit = preview.lines.reduce((sum, l) => sum + l.credit, 0);
                return (
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={0}>
                      <Text strong>Total</Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align="right">
                      <Text strong style={{ color: accountingColors.debit }}>
                        {formatCurrency(totalDebit)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={2} align="right">
                      <Text strong style={{ color: accountingColors.credit }}>
                        {formatCurrency(totalCredit)}
                      </Text>
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                );
              }}
            />
          </div>
        </>
      )}
    </Modal>
  );
}

export default QuickBookModal;
