import { useState } from 'react';
import {
  Typography,
  Button,
  Space,
  DatePicker,
  Select,
  Modal,
  Form,
  Input,
  InputNumber,
  message,
  Tag,
  Tooltip,
  Dropdown,
} from 'antd';
import {
  PlusOutlined,
  FilterOutlined,
  EyeOutlined,
  EditOutlined,
  CopyOutlined,
  DeleteOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import DataTable, { DataTableColumn } from '@/components/tables/DataTable';
import { useCompany } from '@/hooks/useCompany';
import { formatCurrency } from '@/lib/formatters';
import { validateDoubleEntry } from '@/lib/accounting';
import type { Transaction, TransactionLine, Account } from '@/types/accounting';

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

// Mock data - will be replaced with GraphQL queries
const mockAccounts: Account[] = [
  { id: '1', companyId: '1', accountNumber: '1000', name: 'Bank', type: 'asset', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '2', companyId: '1', accountNumber: '1100', name: 'Debitorer', type: 'asset', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '3', companyId: '1', accountNumber: '2000', name: 'Kreditorer', type: 'liability', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '4', companyId: '1', accountNumber: '4000', name: 'Salg af varer', type: 'revenue', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '5', companyId: '1', accountNumber: '5000', name: 'Varekøb', type: 'cogs', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '6', companyId: '1', accountNumber: '6100', name: 'Husleje', type: 'expense', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
  { id: '7', companyId: '1', accountNumber: '6800', name: 'Kontorartikler', type: 'expense', isActive: true, balance: 0, createdAt: '', updatedAt: '' },
];

const mockTransactions: Transaction[] = [
  {
    id: '1',
    companyId: '1',
    transactionNumber: '2025-0001',
    date: '2025-01-15',
    description: 'Salg faktura #1234',
    lines: [
      { id: '1-1', transactionId: '1', accountId: '2', debit: 15625, credit: 0, description: 'Debitor' },
      { id: '1-2', transactionId: '1', accountId: '4', debit: 0, credit: 12500, description: 'Salg' },
      { id: '1-3', transactionId: '1', accountId: '8', debit: 0, credit: 3125, description: 'Moms' },
    ],
    isReconciled: true,
    isVoided: false,
    attachments: [],
    createdAt: '2025-01-15T10:00:00Z',
    updatedAt: '2025-01-15T10:00:00Z',
    createdBy: 'user1',
  },
  {
    id: '2',
    companyId: '1',
    transactionNumber: '2025-0002',
    date: '2025-01-14',
    description: 'Husleje januar 2025',
    lines: [
      { id: '2-1', transactionId: '2', accountId: '6', debit: 15000, credit: 0, description: 'Husleje' },
      { id: '2-2', transactionId: '2', accountId: '1', debit: 0, credit: 15000, description: 'Bank' },
    ],
    isReconciled: false,
    isVoided: false,
    attachments: [],
    createdAt: '2025-01-14T09:00:00Z',
    updatedAt: '2025-01-14T09:00:00Z',
    createdBy: 'user1',
  },
  {
    id: '3',
    companyId: '1',
    transactionNumber: '2025-0003',
    date: '2025-01-13',
    description: 'Køb af kontorartikler',
    lines: [
      { id: '3-1', transactionId: '3', accountId: '7', debit: 500, credit: 0, description: 'Kontorartikler' },
      { id: '3-2', transactionId: '3', accountId: '1', debit: 0, credit: 500, description: 'Bank' },
    ],
    isReconciled: true,
    isVoided: false,
    attachments: [],
    createdAt: '2025-01-13T14:00:00Z',
    updatedAt: '2025-01-13T14:00:00Z',
    createdBy: 'user1',
  },
];

// Extend transaction with calculated fields for display
interface TransactionDisplay extends Transaction {
  totalDebit: number;
  totalCredit: number;
}

export default function Kassekladde() {
  const { company } = useCompany();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingTransaction, setEditingTransaction] = useState<Transaction | null>(null);
  const [dateFilter, setDateFilter] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
  const [form] = Form.useForm();
  const [lines, setLines] = useState<Partial<TransactionLine>[]>([
    { debit: 0, credit: 0 },
    { debit: 0, credit: 0 },
  ]);

  // Process transactions for display
  const displayData: TransactionDisplay[] = mockTransactions.map((tx) => ({
    ...tx,
    totalDebit: tx.lines.reduce((sum, line) => sum + (line.debit || 0), 0),
    totalCredit: tx.lines.reduce((sum, line) => sum + (line.credit || 0), 0),
  }));

  const columns: DataTableColumn<TransactionDisplay>[] = [
    {
      dataIndex: 'transactionNumber',
      title: 'Bilagsnr.',
      width: 120,
      sortable: true,
      render: (value) => <Text strong>#{value as string}</Text>,
    },
    {
      dataIndex: 'date',
      title: 'Dato',
      width: 100,
      sortable: true,
      columnType: 'date',
    },
    {
      dataIndex: 'description',
      title: 'Beskrivelse',
      ellipsis: true,
    },
    {
      dataIndex: 'totalDebit',
      title: 'Debet',
      width: 120,
      sortable: true,
      columnType: 'currency',
    },
    {
      dataIndex: 'totalCredit',
      title: 'Kredit',
      width: 120,
      sortable: true,
      columnType: 'currency',
    },
    {
      dataIndex: 'isReconciled',
      title: 'Status',
      width: 100,
      render: (value, record) => {
        if (record.isVoided) {
          return <Tag color="red">Annulleret</Tag>;
        }
        return value ? (
          <Tag color="green">Afstemt</Tag>
        ) : (
          <Tag color="orange">Uafstemt</Tag>
        );
      },
    },
    {
      dataIndex: 'id',
      title: '',
      width: 50,
      render: (_, record) => {
        const menuItems: MenuProps['items'] = [
          {
            key: 'view',
            icon: <EyeOutlined />,
            label: 'Vis detaljer',
          },
          {
            key: 'edit',
            icon: <EditOutlined />,
            label: 'Rediger',
            disabled: record.isReconciled || record.isVoided,
          },
          {
            key: 'copy',
            icon: <CopyOutlined />,
            label: 'Kopier',
          },
          {
            type: 'divider',
          },
          {
            key: 'void',
            icon: <DeleteOutlined />,
            label: 'Annuller',
            danger: true,
            disabled: record.isVoided,
          },
        ];

        return (
          <Dropdown
            menu={{
              items: menuItems,
              onClick: ({ key }) => handleAction(key, record),
            }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} size="small" />
          </Dropdown>
        );
      },
    },
  ];

  const handleAction = (action: string, record: TransactionDisplay) => {
    switch (action) {
      case 'view':
        // TODO: Show transaction details modal
        message.info(`Vis detaljer for bilag ${record.transactionNumber}`);
        break;
      case 'edit':
        setEditingTransaction(record);
        setIsModalOpen(true);
        break;
      case 'copy':
        // TODO: Copy transaction
        message.success(`Bilag ${record.transactionNumber} kopieret`);
        break;
      case 'void':
        Modal.confirm({
          title: 'Annuller bilag',
          content: `Er du sikker på at du vil annullere bilag ${record.transactionNumber}?`,
          okText: 'Annuller bilag',
          okType: 'danger',
          cancelText: 'Fortryd',
          onOk: () => {
            message.success(`Bilag ${record.transactionNumber} annulleret`);
          },
        });
        break;
    }
  };

  const handleAddLine = () => {
    setLines([...lines, { debit: 0, credit: 0 }]);
  };

  const handleRemoveLine = (index: number) => {
    if (lines.length > 2) {
      setLines(lines.filter((_, i) => i !== index));
    }
  };

  const handleLineChange = (index: number, field: string, value: unknown) => {
    const newLines = [...lines];
    newLines[index] = { ...newLines[index], [field]: value };

    // Auto-balance: if debit is entered, clear credit and vice versa
    if (field === 'debit' && value) {
      newLines[index].credit = 0;
    } else if (field === 'credit' && value) {
      newLines[index].debit = 0;
    }

    setLines(newLines);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // Validate double-entry
      const validation = validateDoubleEntry(lines as TransactionLine[]);
      if (!validation.valid) {
        message.error(
          `Debet (${formatCurrency(validation.totalDebit)}) skal være lig kredit (${formatCurrency(validation.totalCredit)})`
        );
        return;
      }

      // TODO: Submit via GraphQL mutation
      console.log('Submitting:', { ...values, lines });
      message.success('Bilag oprettet');
      setIsModalOpen(false);
      form.resetFields();
      setLines([{ debit: 0, credit: 0 }, { debit: 0, credit: 0 }]);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const balance = validateDoubleEntry(lines as TransactionLine[]);

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Kassekladde
          </Title>
          <Text type="secondary">{company?.name}</Text>
        </div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setEditingTransaction(null);
            setIsModalOpen(true);
          }}
        >
          Nyt bilag
        </Button>
      </div>

      {/* Filters */}
      <Space style={{ marginBottom: 16 }} wrap>
        <RangePicker
          placeholder={['Fra dato', 'Til dato']}
          value={dateFilter}
          onChange={(dates) => setDateFilter(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
          format="DD/MM/YYYY"
        />
        <Select
          placeholder="Konto"
          style={{ width: 200 }}
          allowClear
          options={mockAccounts.map((acc) => ({
            value: acc.id,
            label: `${acc.accountNumber} - ${acc.name}`,
          }))}
        />
        <Select
          placeholder="Status"
          style={{ width: 120 }}
          allowClear
          options={[
            { value: 'reconciled', label: 'Afstemt' },
            { value: 'unreconciled', label: 'Uafstemt' },
            { value: 'voided', label: 'Annulleret' },
          ]}
        />
        <Button icon={<FilterOutlined />}>Flere filtre</Button>
      </Space>

      {/* Data Table */}
      <DataTable<TransactionDisplay>
        data={displayData}
        columns={columns}
        exportFilename="kassekladde"
        rowSelection="multiple"
        onRowClick={(record) => handleAction('view', record)}
        rowClassName={(record) =>
          record.isVoided ? 'voided-row' : ''
        }
      />

      {/* Create/Edit Modal */}
      <Modal
        title={editingTransaction ? 'Rediger bilag' : 'Nyt bilag'}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
          form.resetFields();
          setLines([{ debit: 0, credit: 0 }, { debit: 0, credit: 0 }]);
        }}
        onOk={handleSubmit}
        okText="Gem"
        cancelText="Annuller"
        width={800}
      >
        <Form form={form} layout="vertical">
          <Space style={{ width: '100%' }} direction="vertical" size="middle">
            <Space style={{ width: '100%' }}>
              <Form.Item
                name="date"
                label="Dato"
                rules={[{ required: true, message: 'Vælg dato' }]}
                initialValue={dayjs()}
              >
                <DatePicker format="DD/MM/YYYY" style={{ width: 150 }} />
              </Form.Item>
              <Form.Item
                name="description"
                label="Beskrivelse"
                rules={[{ required: true, message: 'Indtast beskrivelse' }]}
                style={{ flex: 1 }}
              >
                <Input placeholder="F.eks. Faktura #1234 til kunde" />
              </Form.Item>
            </Space>

            {/* Transaction Lines */}
            <div>
              <Text strong style={{ display: 'block', marginBottom: 8 }}>
                Posteringslinjer
              </Text>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ borderBottom: '1px solid #f0f0f0' }}>
                    <th style={{ textAlign: 'left', padding: 8, width: '40%' }}>Konto</th>
                    <th style={{ textAlign: 'right', padding: 8, width: '20%' }}>Debet</th>
                    <th style={{ textAlign: 'right', padding: 8, width: '20%' }}>Kredit</th>
                    <th style={{ textAlign: 'left', padding: 8, width: '15%' }}>Tekst</th>
                    <th style={{ width: '5%' }}></th>
                  </tr>
                </thead>
                <tbody>
                  {lines.map((line, index) => (
                    <tr key={index}>
                      <td style={{ padding: 4 }}>
                        <Select
                          style={{ width: '100%' }}
                          placeholder="Vælg konto"
                          showSearch
                          optionFilterProp="label"
                          value={line.accountId}
                          onChange={(value) => handleLineChange(index, 'accountId', value)}
                          options={mockAccounts.map((acc) => ({
                            value: acc.id,
                            label: `${acc.accountNumber} - ${acc.name}`,
                          }))}
                        />
                      </td>
                      <td style={{ padding: 4 }}>
                        <InputNumber
                          style={{ width: '100%' }}
                          min={0}
                          precision={2}
                          value={line.debit}
                          onChange={(value) => handleLineChange(index, 'debit', value || 0)}
                          formatter={(value) =>
                            `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
                          }
                          parser={(value) =>
                            value?.replace(/\./g, '').replace(',', '.') as unknown as number
                          }
                        />
                      </td>
                      <td style={{ padding: 4 }}>
                        <InputNumber
                          style={{ width: '100%' }}
                          min={0}
                          precision={2}
                          value={line.credit}
                          onChange={(value) => handleLineChange(index, 'credit', value || 0)}
                          formatter={(value) =>
                            `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
                          }
                          parser={(value) =>
                            value?.replace(/\./g, '').replace(',', '.') as unknown as number
                          }
                        />
                      </td>
                      <td style={{ padding: 4 }}>
                        <Input
                          placeholder="Valgfri"
                          value={line.description}
                          onChange={(e) =>
                            handleLineChange(index, 'description', e.target.value)
                          }
                        />
                      </td>
                      <td style={{ padding: 4 }}>
                        {lines.length > 2 && (
                          <Button
                            type="text"
                            danger
                            size="small"
                            onClick={() => handleRemoveLine(index)}
                          >
                            ×
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr style={{ borderTop: '2px solid #f0f0f0' }}>
                    <td style={{ padding: 8 }}>
                      <Button type="dashed" size="small" onClick={handleAddLine}>
                        + Tilføj linje
                      </Button>
                    </td>
                    <td
                      style={{
                        padding: 8,
                        textAlign: 'right',
                        fontWeight: 'bold',
                      }}
                    >
                      {formatCurrency(balance.totalDebit)}
                    </td>
                    <td
                      style={{
                        padding: 8,
                        textAlign: 'right',
                        fontWeight: 'bold',
                      }}
                    >
                      {formatCurrency(balance.totalCredit)}
                    </td>
                    <td colSpan={2} style={{ padding: 8 }}>
                      {!balance.valid && (
                        <Tooltip title={`Difference: ${formatCurrency(balance.difference)}`}>
                          <Tag color="red">Ubalance!</Tag>
                        </Tooltip>
                      )}
                      {balance.valid && balance.totalDebit > 0 && (
                        <Tag color="green">Balancerer</Tag>
                      )}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </Space>
        </Form>
      </Modal>
    </div>
  );
}
