import { useState } from 'react';
import {
  Typography,
  Button,
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Space,
  List,
  Checkbox,
  Tag,
  Statistic,
  Modal,
  Form,
  Input,
  message,
  Tooltip,
  Alert,
} from 'antd';
import {
  SwapOutlined,
  PlusOutlined,
  UndoOutlined,
  CheckOutlined,
  LinkOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useCompany } from '@/hooks/useCompany';
import { useReconciliationStore } from '@/stores/reconciliationStore';
import { formatCurrency, formatDate } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import type { BankTransaction, BankAccount } from '@/types/accounting';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

// Mock data
const mockBankAccounts: BankAccount[] = [
  {
    id: '1',
    companyId: '1',
    name: 'Erhvervskonto',
    bankName: 'Danske Bank',
    accountNumber: '1234-5678901234',
    iban: 'DK1234567890123456',
    currency: 'DKK',
    ledgerAccountId: '1',
    isActive: true,
  },
  {
    id: '2',
    companyId: '1',
    name: 'Opsparingskonto',
    bankName: 'Nordea',
    accountNumber: '9876-5432109876',
    iban: 'DK9876543210987654',
    currency: 'DKK',
    ledgerAccountId: '2',
    isActive: true,
  },
];

const mockBankTransactions: BankTransaction[] = [
  {
    id: 'bt1',
    bankAccountId: '1',
    date: '2025-01-15',
    valueDate: '2025-01-15',
    description: 'FAKTURA 1234 FRA KUNDE A/S',
    amount: 15625,
    balance: 156250,
    reference: 'FI1234',
    counterparty: 'Kunde A/S',
    isReconciled: false,
    importedAt: '2025-01-16T08:00:00Z',
  },
  {
    id: 'bt2',
    bankAccountId: '1',
    date: '2025-01-14',
    valueDate: '2025-01-14',
    description: 'HUSLEJE JANUAR EJENDOM APS',
    amount: -15000,
    balance: 140625,
    reference: 'BS123456',
    counterparty: 'Ejendom ApS',
    isReconciled: false,
    importedAt: '2025-01-16T08:00:00Z',
  },
  {
    id: 'bt3',
    bankAccountId: '1',
    date: '2025-01-13',
    valueDate: '2025-01-13',
    description: 'MOBILEPAY STAPLES',
    amount: -499,
    balance: 155625,
    counterparty: 'Staples',
    isReconciled: false,
    importedAt: '2025-01-16T08:00:00Z',
  },
  {
    id: 'bt4',
    bankAccountId: '1',
    date: '2025-01-10',
    valueDate: '2025-01-10',
    description: 'OVERFOERSEL FRA DEBITOR',
    amount: 8750,
    balance: 156124,
    reference: 'FAKTURA1233',
    counterparty: 'Debitor B ApS',
    isReconciled: true,
    matchedTransactionId: 'tx3',
    importedAt: '2025-01-11T08:00:00Z',
  },
];

const mockLedgerEntries = [
  {
    id: 'le1',
    date: '2025-01-15',
    description: 'Faktura #1234 - Kunde A/S',
    amount: 15625,
    accountId: '1',
    accountName: '1000 Bank',
    transactionNumber: '2025-0001',
    isReconciled: false,
  },
  {
    id: 'le2',
    date: '2025-01-14',
    description: 'Husleje januar 2025',
    amount: -15000,
    accountId: '1',
    accountName: '1000 Bank',
    transactionNumber: '2025-0002',
    isReconciled: false,
  },
  {
    id: 'le3',
    date: '2025-01-12',
    description: 'Kontorartikler',
    amount: -500,
    accountId: '1',
    accountName: '1000 Bank',
    transactionNumber: '2025-0003',
    isReconciled: false,
  },
];

// Match suggestions (would come from backend AI/rules)
const mockSuggestions = [
  {
    bankTransactionId: 'bt1',
    ledgerEntryId: 'le1',
    confidence: 0.95,
    reason: 'Beløb og dato matcher, "Faktura 1234" findes i begge',
  },
  {
    bankTransactionId: 'bt2',
    ledgerEntryId: 'le2',
    confidence: 0.88,
    reason: 'Beløb matcher, begge er husleje i januar',
  },
];


export default function Bankafstemning() {
  const { company } = useCompany();
  const [selectedBankAccount, setSelectedBankAccount] = useState<string>(mockBankAccounts[0].id);
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().startOf('month'),
    dayjs().endOf('month'),
  ]);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [selectedBankTx, setSelectedBankTx] = useState<BankTransaction | null>(null);
  const [form] = Form.useForm();

  const {
    selectedBankTransactions,
    selectedLedgerTransactions,
    toggleBankTransaction,
    toggleLedgerTransaction,
    clearAllSelections,
    pendingMatches,
    addPendingMatch,
    removePendingMatch,
  } = useReconciliationStore();

  // Filter transactions
  const bankTransactions = mockBankTransactions.filter(
    (tx) => tx.bankAccountId === selectedBankAccount && !tx.isReconciled
  );
  const ledgerEntries = mockLedgerEntries.filter((entry) => !entry.isReconciled);

  // Calculate totals
  const bankTotal = bankTransactions.reduce((sum, tx) => sum + tx.amount, 0);
  const ledgerTotal = ledgerEntries.reduce((sum, entry) => sum + entry.amount, 0);
  const difference = bankTotal - ledgerTotal;

  // Check if selected items can be matched
  const canMatch =
    selectedBankTransactions.length === 1 && selectedLedgerTransactions.length === 1;

  // Get suggestion for a bank transaction
  const getSuggestion = (bankTxId: string) => {
    return mockSuggestions.find((s) => s.bankTransactionId === bankTxId);
  };

  const handleMatch = () => {
    if (!canMatch) return;

    const bankTx = bankTransactions.find((tx) => tx.id === selectedBankTransactions[0]);
    const ledgerEntry = ledgerEntries.find((e) => e.id === selectedLedgerTransactions[0]);

    if (bankTx && ledgerEntry) {
      addPendingMatch({
        bankTransactionId: bankTx.id,
        ledgerTransactionId: ledgerEntry.id,
        matchType: 'existing',
      });
      message.success('Match tilføjet');
    }
  };

  const handleCreateEntry = (bankTx: BankTransaction) => {
    setSelectedBankTx(bankTx);
    form.setFieldsValue({
      date: dayjs(bankTx.date),
      description: bankTx.description,
      amount: Math.abs(bankTx.amount),
    });
    setIsCreateModalOpen(true);
  };

  const handleSubmitCreate = async () => {
    try {
      const values = await form.validateFields();
      console.log('Creating entry:', values);

      if (selectedBankTx) {
        addPendingMatch({
          bankTransactionId: selectedBankTx.id,
          matchType: 'new',
          newTransaction: {
            description: values.description,
            accountId: values.accountId,
          },
        });
      }

      message.success('Postering oprettet og matchet');
      setIsCreateModalOpen(false);
      setSelectedBankTx(null);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleSaveAll = () => {
    if (pendingMatches.length === 0) {
      message.warning('Ingen matches at gemme');
      return;
    }
    // TODO: Send to GraphQL mutation
    console.log('Saving matches:', pendingMatches);
    message.success(`${pendingMatches.length} afstemninger gemt`);
  };

  const handleApplySuggestion = (suggestion: typeof mockSuggestions[0]) => {
    addPendingMatch({
      bankTransactionId: suggestion.bankTransactionId,
      ledgerTransactionId: suggestion.ledgerEntryId,
      matchType: 'existing',
    });
    message.success('Forslag anvendt');
  };

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Bankafstemning
          </Title>
          <Text type="secondary">{company?.name}</Text>
        </div>
        <Space>
          <Button
            icon={<UndoOutlined />}
            onClick={clearAllSelections}
            disabled={
              selectedBankTransactions.length === 0 &&
              selectedLedgerTransactions.length === 0
            }
          >
            Nulstil valg
          </Button>
          <Button
            type="primary"
            icon={<CheckOutlined />}
            onClick={handleSaveAll}
            disabled={pendingMatches.length === 0}
          >
            Gem afstemninger ({pendingMatches.length})
          </Button>
        </Space>
      </div>

      {/* Filters */}
      <Space style={{ marginBottom: 16 }} wrap>
        <Select
          value={selectedBankAccount}
          onChange={setSelectedBankAccount}
          style={{ width: 250 }}
          options={mockBankAccounts.map((acc) => ({
            value: acc.id,
            label: `${acc.bankName} - ${acc.name}`,
          }))}
        />
        <RangePicker
          value={dateRange}
          onChange={(dates) => setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs])}
          format="DD/MM/YYYY"
        />
      </Space>

      {/* Summary */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Bank (uafstemt)"
              value={bankTotal}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color: bankTotal >= 0 ? accountingColors.credit : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Bogføring (uafstemt)"
              value={ledgerTotal}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color: ledgerTotal >= 0 ? accountingColors.credit : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Difference"
              value={difference}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color:
                  Math.abs(difference) < 0.01
                    ? accountingColors.credit
                    : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* Suggestions Alert */}
      {mockSuggestions.length > 0 && (
        <Alert
          message={
            <Space>
              <BulbOutlined />
              <Text strong>{mockSuggestions.length} automatiske matchforslag fundet</Text>
            </Space>
          }
          type="info"
          style={{ marginBottom: 16 }}
          action={
            <Button
              size="small"
              onClick={() => mockSuggestions.forEach(handleApplySuggestion)}
            >
              Anvend alle
            </Button>
          }
        />
      )}

      {/* Match Button */}
      <div style={{ textAlign: 'center', marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<LinkOutlined />}
          size="large"
          onClick={handleMatch}
          disabled={!canMatch}
        >
          Match valgte ({selectedBankTransactions.length} bank,{' '}
          {selectedLedgerTransactions.length} bogføring)
        </Button>
      </div>

      {/* Side-by-side panels */}
      <Row gutter={16}>
        {/* Bank Transactions */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <Text strong>Banktransaktioner</Text>
                <Tag color="blue">{bankTransactions.length} uafstemte</Tag>
              </Space>
            }
            size="small"
            bodyStyle={{ padding: 0, maxHeight: 500, overflow: 'auto' }}
          >
            <List
              dataSource={bankTransactions}
              renderItem={(tx) => {
                const suggestion = getSuggestion(tx.id);
                const isPending = pendingMatches.some(
                  (m) => m.bankTransactionId === tx.id
                );
                const isSelected = selectedBankTransactions.includes(tx.id);

                if (isPending) return null;

                return (
                  <List.Item
                    style={{
                      padding: '8px 16px',
                      cursor: 'pointer',
                      backgroundColor: isSelected ? '#e6f4ff' : undefined,
                    }}
                    onClick={() => toggleBankTransaction(tx.id)}
                  >
                    <div style={{ width: '100%' }}>
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'flex-start',
                        }}
                      >
                        <Space>
                          <Checkbox checked={isSelected} />
                          <div>
                            <Text style={{ display: 'block' }}>
                              {tx.description}
                            </Text>
                            <Text type="secondary" style={{ fontSize: 12 }}>
                              {formatDate(tx.date)} • {tx.counterparty || 'Ukendt'}
                            </Text>
                          </div>
                        </Space>
                        <div style={{ textAlign: 'right' }}>
                          <Text
                            strong
                            className="tabular-nums"
                            style={{
                              color:
                                tx.amount >= 0
                                  ? accountingColors.credit
                                  : accountingColors.debit,
                            }}
                          >
                            {formatCurrency(tx.amount, { showSign: true })}
                          </Text>
                          {suggestion && (
                            <div>
                              <Tooltip title={suggestion.reason}>
                                <Tag
                                  color="green"
                                  style={{ cursor: 'pointer', marginTop: 4 }}
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    handleApplySuggestion(suggestion);
                                  }}
                                >
                                  <BulbOutlined />{' '}
                                  {Math.round(suggestion.confidence * 100)}% match
                                </Tag>
                              </Tooltip>
                            </div>
                          )}
                        </div>
                      </div>
                      <div style={{ marginTop: 4 }}>
                        <Button
                          type="link"
                          size="small"
                          icon={<PlusOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleCreateEntry(tx);
                          }}
                        >
                          Opret postering
                        </Button>
                      </div>
                    </div>
                  </List.Item>
                );
              }}
            />
          </Card>
        </Col>

        {/* Ledger Entries */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <Text strong>Bogføringsposter</Text>
                <Tag color="orange">{ledgerEntries.length} uafstemte</Tag>
              </Space>
            }
            size="small"
            bodyStyle={{ padding: 0, maxHeight: 500, overflow: 'auto' }}
          >
            <List
              dataSource={ledgerEntries}
              renderItem={(entry) => {
                const isPending = pendingMatches.some(
                  (m) => m.ledgerTransactionId === entry.id
                );
                const isSelected = selectedLedgerTransactions.includes(entry.id);

                if (isPending) return null;

                return (
                  <List.Item
                    style={{
                      padding: '8px 16px',
                      cursor: 'pointer',
                      backgroundColor: isSelected ? '#e6f4ff' : undefined,
                    }}
                    onClick={() => toggleLedgerTransaction(entry.id)}
                  >
                    <div style={{ width: '100%' }}>
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'flex-start',
                        }}
                      >
                        <Space>
                          <Checkbox checked={isSelected} />
                          <div>
                            <Text style={{ display: 'block' }}>
                              {entry.description}
                            </Text>
                            <Text type="secondary" style={{ fontSize: 12 }}>
                              {formatDate(entry.date)} • Bilag{' '}
                              {entry.transactionNumber}
                            </Text>
                          </div>
                        </Space>
                        <Text
                          strong
                          className="tabular-nums"
                          style={{
                            color:
                              entry.amount >= 0
                                ? accountingColors.credit
                                : accountingColors.debit,
                          }}
                        >
                          {formatCurrency(entry.amount, { showSign: true })}
                        </Text>
                      </div>
                    </div>
                  </List.Item>
                );
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* Pending Matches */}
      {pendingMatches.length > 0 && (
        <Card
          title={
            <Space>
              <Text strong>Afventende matches</Text>
              <Tag color="blue">{pendingMatches.length}</Tag>
            </Space>
          }
          size="small"
          style={{ marginTop: 16 }}
        >
          <List
            dataSource={pendingMatches}
            renderItem={(match) => {
              const bankTx = mockBankTransactions.find(
                (tx) => tx.id === match.bankTransactionId
              );
              const ledgerEntry = mockLedgerEntries.find(
                (e) => e.id === match.ledgerTransactionId
              );

              return (
                <List.Item
                  actions={[
                    <Button
                      type="link"
                      danger
                      size="small"
                      onClick={() => removePendingMatch(match.bankTransactionId)}
                    >
                      Fjern
                    </Button>,
                  ]}
                >
                  <Space split={<SwapOutlined />}>
                    <Text>
                      Bank: {bankTx?.description} ({formatCurrency(bankTx?.amount || 0)})
                    </Text>
                    {match.matchType === 'existing' ? (
                      <Text>
                        Bilag: {ledgerEntry?.transactionNumber} - {ledgerEntry?.description}
                      </Text>
                    ) : (
                      <Tag color="green">Ny postering oprettes</Tag>
                    )}
                  </Space>
                </List.Item>
              );
            }}
          />
        </Card>
      )}

      {/* Create Entry Modal */}
      <Modal
        title="Opret bogføringspost"
        open={isCreateModalOpen}
        onCancel={() => {
          setIsCreateModalOpen(false);
          setSelectedBankTx(null);
        }}
        onOk={handleSubmitCreate}
        okText="Opret og match"
        cancelText="Annuller"
      >
        {selectedBankTx && (
          <Alert
            message={
              <Space direction="vertical" size={0}>
                <Text>Banktransaktion:</Text>
                <Text strong>{selectedBankTx.description}</Text>
                <Text>
                  {formatDate(selectedBankTx.date)} •{' '}
                  {formatCurrency(selectedBankTx.amount, { showSign: true })}
                </Text>
              </Space>
            }
            type="info"
            style={{ marginBottom: 16 }}
          />
        )}
        <Form form={form} layout="vertical">
          <Form.Item
            name="date"
            label="Dato"
            rules={[{ required: true }]}
          >
            <DatePicker format="DD/MM/YYYY" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="description"
            label="Beskrivelse"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="accountId"
            label="Modkonto"
            rules={[{ required: true }]}
          >
            <Select
              placeholder="Vælg konto"
              options={[
                { value: '6100', label: '6100 - Husleje' },
                { value: '6800', label: '6800 - Kontorartikler' },
                { value: '5000', label: '5000 - Varekøb' },
                { value: '4000', label: '4000 - Salg' },
              ]}
            />
          </Form.Item>
          <Form.Item name="vatCode" label="Momskode">
            <Select
              placeholder="Vælg momskode"
              allowClear
              options={[
                { value: 'K25', label: 'K25 - Indgående moms 25%' },
                { value: 'S25', label: 'S25 - Udgående moms 25%' },
                { value: 'NONE', label: 'Ingen moms' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
