import { useState } from 'react';
import {
  Typography,
  Button,
  Card,
  Row,
  Col,
  Tree,
  Table,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Tabs,
  Statistic,
  message,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  FolderOutlined,
  FileOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import { useCompany } from '@/hooks/useCompany';
import { formatCurrency, formatDate } from '@/lib/formatters';
import { getAccountTypeName, getAccountNumberRange } from '@/lib/accounting';
import { accountingColors } from '@/styles/theme';
import type { Account, AccountType } from '@/types/accounting';

const { Title, Text } = Typography;

// Mock data
const mockAccounts: Account[] = [
  { id: '1', companyId: '1', accountNumber: '1000', name: 'Bankkonto', type: 'asset', isActive: true, balance: 125000, createdAt: '', updatedAt: '' },
  { id: '2', companyId: '1', accountNumber: '1100', name: 'Debitorer', type: 'asset', isActive: true, balance: 45000, createdAt: '', updatedAt: '' },
  { id: '3', companyId: '1', accountNumber: '1200', name: 'Varelager', type: 'asset', isActive: true, balance: 75000, createdAt: '', updatedAt: '' },
  { id: '4', companyId: '1', accountNumber: '2000', name: 'Kreditorer', type: 'liability', isActive: true, balance: -35000, createdAt: '', updatedAt: '' },
  { id: '5', companyId: '1', accountNumber: '2100', name: 'Moms', type: 'liability', isActive: true, balance: -12500, createdAt: '', updatedAt: '' },
  { id: '6', companyId: '1', accountNumber: '3000', name: 'Egenkapital', type: 'equity', isActive: true, balance: -100000, createdAt: '', updatedAt: '' },
  { id: '7', companyId: '1', accountNumber: '4000', name: 'Salg af varer', type: 'revenue', isActive: true, balance: -250000, createdAt: '', updatedAt: '' },
  { id: '8', companyId: '1', accountNumber: '5000', name: 'Varekøb', type: 'cogs', isActive: true, balance: 80000, createdAt: '', updatedAt: '' },
  { id: '9', companyId: '1', accountNumber: '6100', name: 'Husleje', type: 'expense', isActive: true, balance: 60000, createdAt: '', updatedAt: '' },
  { id: '10', companyId: '1', accountNumber: '6200', name: 'El og varme', type: 'expense', isActive: true, balance: 8000, createdAt: '', updatedAt: '' },
  { id: '11', companyId: '1', accountNumber: '7000', name: 'Lønninger', type: 'personnel', isActive: true, balance: 120000, createdAt: '', updatedAt: '' },
  { id: '12', companyId: '1', accountNumber: '8100', name: 'Renteindtægter', type: 'financial', isActive: true, balance: -500, createdAt: '', updatedAt: '' },
];

const mockTransactions: { accountId: string; date: string; description: string; debit: number; credit: number; balance: number }[] = [
  { accountId: '1', date: '2025-01-15', description: 'Faktura #1234 modtaget', debit: 15625, credit: 0, balance: 140625 },
  { accountId: '1', date: '2025-01-14', description: 'Husleje januar', debit: 0, credit: 15000, balance: 125000 },
  { accountId: '1', date: '2025-01-13', description: 'Kontorartikler', debit: 0, credit: 500, balance: 140000 },
  { accountId: '1', date: '2025-01-10', description: 'Salg #1233', debit: 8750, credit: 0, balance: 140500 },
  { accountId: '1', date: '2025-01-05', description: 'Lønudbetaling', debit: 0, credit: 45000, balance: 131750 },
];

const accountTypes: AccountType[] = [
  'asset',
  'liability',
  'equity',
  'revenue',
  'cogs',
  'expense',
  'personnel',
  'financial',
  'extraordinary',
];

export default function Kontooversigt() {
  const { company } = useCompany();
  const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingAccount, setEditingAccount] = useState<Account | null>(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  // Build tree data from accounts
  const buildTreeData = (): DataNode[] => {
    return accountTypes.map((type) => {
      const range = getAccountNumberRange(type);
      const typeAccounts = mockAccounts.filter((acc) => acc.type === type);
      const typeBalance = typeAccounts.reduce((sum, acc) => sum + acc.balance, 0);

      return {
        key: type,
        title: (
          <Space>
            <Text strong>{getAccountTypeName(type)}</Text>
            <Text type="secondary">({range.min}-{range.max})</Text>
            <Text
              className="tabular-nums"
              style={{
                color: typeBalance >= 0 ? accountingColors.credit : accountingColors.debit,
              }}
            >
              {formatCurrency(Math.abs(typeBalance))}
            </Text>
          </Space>
        ),
        icon: <FolderOutlined />,
        children: typeAccounts
          .filter((acc) =>
            searchText === '' ||
            acc.name.toLowerCase().includes(searchText.toLowerCase()) ||
            acc.accountNumber.includes(searchText)
          )
          .map((acc) => ({
            key: acc.id,
            title: (
              <Space>
                <Text code>{acc.accountNumber}</Text>
                <Text>{acc.name}</Text>
                {!acc.isActive && <Tag color="red">Inaktiv</Tag>}
                <Text
                  className="tabular-nums"
                  style={{
                    color: acc.balance >= 0 ? accountingColors.credit : accountingColors.debit,
                  }}
                >
                  {formatCurrency(Math.abs(acc.balance))}
                </Text>
              </Space>
            ),
            icon: <FileOutlined />,
            isLeaf: true,
          })),
      };
    });
  };

  const handleSelectAccount = (selectedKeys: React.Key[]) => {
    const key = selectedKeys[0];
    if (key && !accountTypes.includes(key as AccountType)) {
      const account = mockAccounts.find((acc) => acc.id === key);
      setSelectedAccount(account || null);
    }
  };

  const handleCreateAccount = () => {
    setEditingAccount(null);
    form.resetFields();
    setIsModalOpen(true);
  };

  const handleEditAccount = (account: Account) => {
    setEditingAccount(account);
    form.setFieldsValue(account);
    setIsModalOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log('Submitting account:', values);
      message.success(editingAccount ? 'Konto opdateret' : 'Konto oprettet');
      setIsModalOpen(false);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  // Account transactions for selected account
  const accountTransactions = selectedAccount
    ? mockTransactions.filter((tx) => tx.accountId === selectedAccount.id)
    : [];

  const transactionColumns = [
    {
      dataIndex: 'date',
      title: 'Dato',
      width: 100,
      render: (value: string) => formatDate(value),
    },
    {
      dataIndex: 'description',
      title: 'Beskrivelse',
      ellipsis: true,
    },
    {
      dataIndex: 'debit',
      title: 'Debet',
      width: 120,
      align: 'right' as const,
      render: (value: number) =>
        value > 0 ? (
          <span className="tabular-nums">{formatCurrency(value)}</span>
        ) : null,
    },
    {
      dataIndex: 'credit',
      title: 'Kredit',
      width: 120,
      align: 'right' as const,
      render: (value: number) =>
        value > 0 ? (
          <span className="tabular-nums">{formatCurrency(value)}</span>
        ) : null,
    },
    {
      dataIndex: 'balance',
      title: 'Saldo',
      width: 120,
      align: 'right' as const,
      render: (value: number) => (
        <span
          className="tabular-nums"
          style={{
            fontWeight: 'bold',
            color: value >= 0 ? accountingColors.credit : accountingColors.debit,
          }}
        >
          {formatCurrency(value)}
        </span>
      ),
    },
  ];

  // Calculate totals
  const totalAssets = mockAccounts
    .filter((a) => a.type === 'asset')
    .reduce((sum, a) => sum + a.balance, 0);
  const totalLiabilities = mockAccounts
    .filter((a) => ['liability', 'equity'].includes(a.type))
    .reduce((sum, a) => sum + Math.abs(a.balance), 0);
  const totalRevenue = mockAccounts
    .filter((a) => a.type === 'revenue')
    .reduce((sum, a) => sum + Math.abs(a.balance), 0);
  const totalExpenses = mockAccounts
    .filter((a) => ['cogs', 'expense', 'personnel', 'financial'].includes(a.type))
    .reduce((sum, a) => sum + a.balance, 0);

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Kontooversigt
          </Title>
          <Text type="secondary">{company?.name}</Text>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateAccount}>
          Ny konto
        </Button>
      </div>

      {/* Summary Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Aktiver"
              value={totalAssets}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.credit }}
              formatter={(value) => formatCurrency(value as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Passiver"
              value={totalLiabilities}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.debit }}
              formatter={(value) => formatCurrency(value as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Omsætning"
              value={totalRevenue}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.credit }}
              formatter={(value) => formatCurrency(value as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Omkostninger"
              value={totalExpenses}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.debit }}
              formatter={(value) => formatCurrency(value as number)}
            />
          </Card>
        </Col>
      </Row>

      {/* Main Content */}
      <Row gutter={16}>
        {/* Account Tree */}
        <Col xs={24} lg={10}>
          <Card
            title="Kontoplan"
            size="small"
            extra={
              <Input
                placeholder="Søg konto..."
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ width: 200 }}
                allowClear
              />
            }
          >
            <Tree
              showIcon
              defaultExpandAll
              treeData={buildTreeData()}
              onSelect={handleSelectAccount}
              selectedKeys={selectedAccount ? [selectedAccount.id] : []}
              style={{ maxHeight: 500, overflow: 'auto' }}
            />
          </Card>
        </Col>

        {/* Account Details */}
        <Col xs={24} lg={14}>
          {selectedAccount ? (
            <Card
              title={
                <Space>
                  <Text code>{selectedAccount.accountNumber}</Text>
                  <Text strong>{selectedAccount.name}</Text>
                </Space>
              }
              size="small"
              extra={
                <Button
                  icon={<EditOutlined />}
                  onClick={() => handleEditAccount(selectedAccount)}
                >
                  Rediger
                </Button>
              }
            >
              <Tabs
                items={[
                  {
                    key: 'transactions',
                    label: 'Bevægelser',
                    children: (
                      <div>
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            marginBottom: 16,
                          }}
                        >
                          <Statistic
                            title="Saldo"
                            value={selectedAccount.balance}
                            precision={2}
                            formatter={(value) => formatCurrency(value as number)}
                            valueStyle={{
                              color:
                                selectedAccount.balance >= 0
                                  ? accountingColors.credit
                                  : accountingColors.debit,
                            }}
                          />
                        </div>
                        <Table
                          dataSource={accountTransactions}
                          columns={transactionColumns}
                          rowKey={(_, index) => String(index)}
                          size="small"
                          pagination={{ pageSize: 10 }}
                        />
                      </div>
                    ),
                  },
                  {
                    key: 'info',
                    label: 'Kontooplysninger',
                    children: (
                      <div>
                        <Row gutter={[16, 16]}>
                          <Col span={12}>
                            <Text type="secondary">Kontonummer</Text>
                            <div>
                              <Text strong>{selectedAccount.accountNumber}</Text>
                            </div>
                          </Col>
                          <Col span={12}>
                            <Text type="secondary">Kontotype</Text>
                            <div>
                              <Tag>{getAccountTypeName(selectedAccount.type)}</Tag>
                            </div>
                          </Col>
                          <Col span={12}>
                            <Text type="secondary">Status</Text>
                            <div>
                              {selectedAccount.isActive ? (
                                <Tag color="green">Aktiv</Tag>
                              ) : (
                                <Tag color="red">Inaktiv</Tag>
                              )}
                            </div>
                          </Col>
                          <Col span={12}>
                            <Text type="secondary">Momskode</Text>
                            <div>
                              <Text>{selectedAccount.vatCode || 'Ingen'}</Text>
                            </div>
                          </Col>
                        </Row>
                      </div>
                    ),
                  },
                ]}
              />
            </Card>
          ) : (
            <Card size="small">
              <div
                style={{
                  textAlign: 'center',
                  padding: 40,
                  color: '#8c8c8c',
                }}
              >
                <FileOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                <div>Vælg en konto for at se detaljer</div>
              </div>
            </Card>
          )}
        </Col>
      </Row>

      {/* Create/Edit Account Modal */}
      <Modal
        title={editingAccount ? 'Rediger konto' : 'Opret konto'}
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        onOk={handleSubmit}
        okText="Gem"
        cancelText="Annuller"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="accountNumber"
            label="Kontonummer"
            rules={[
              { required: true, message: 'Indtast kontonummer' },
              {
                pattern: /^\d{4}$/,
                message: 'Kontonummer skal være 4 cifre',
              },
            ]}
          >
            <Input placeholder="F.eks. 1000" maxLength={4} />
          </Form.Item>

          <Form.Item
            name="name"
            label="Kontonavn"
            rules={[{ required: true, message: 'Indtast kontonavn' }]}
          >
            <Input placeholder="F.eks. Bankkonto" />
          </Form.Item>

          <Form.Item
            name="type"
            label="Kontotype"
            rules={[{ required: true, message: 'Vælg kontotype' }]}
          >
            <Select
              placeholder="Vælg type"
              options={accountTypes.map((type) => ({
                value: type,
                label: getAccountTypeName(type),
              }))}
            />
          </Form.Item>

          <Form.Item name="vatCode" label="Momskode">
            <Select
              placeholder="Vælg momskode"
              allowClear
              options={[
                { value: 'S25', label: 'S25 - Udgående moms 25%' },
                { value: 'K25', label: 'K25 - Indgående moms 25%' },
                { value: 'E0', label: 'E0 - EU-varekøb 0%' },
                { value: 'U0', label: 'U0 - Eksport 0%' },
              ]}
            />
          </Form.Item>

          <Form.Item name="description" label="Beskrivelse">
            <Input.TextArea rows={2} placeholder="Valgfri beskrivelse" />
          </Form.Item>

          <Form.Item name="isActive" label="Status" initialValue={true}>
            <Select
              options={[
                { value: true, label: 'Aktiv' },
                { value: false, label: 'Inaktiv' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
