import { useState, useMemo } from 'react';
import {
  Typography,
  Button,
  Card,
  Row,
  Col,
  Table,
  Space,
  Tag,
  Drawer,
  Form,
  Input,
  Select,
  Statistic,
  message,
  Switch,
  Divider,
  Descriptions,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  SearchOutlined,
  MoreOutlined,
  HistoryOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { useCompanyStore } from '@/stores/companyStore';
import { usePeriodStore } from '@/stores/periodStore';
import { useAccounts, useAccountBalances } from '@/api/queries/accountQueries';
import { formatCurrency } from '@/lib/formatters';
import { getAccountTypeName } from '@/lib/accounting';
import { accountingColors } from '@/styles/theme';
import { PageHeader } from '@/components/shared/PageHeader';
import type { Account, AccountType } from '@/types/accounting';
import { useCreateAccount } from '@/api/mutations/accountMutations';

const { Text } = Typography;

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

interface AccountWithBalance extends Account {
  balance: number;
}

export default function Kontooversigt() {
  const navigate = useNavigate();
  const { activeCompany } = useCompanyStore();
  const { currentFiscalYear } = usePeriodStore();
  const [selectedAccount, setSelectedAccount] = useState<AccountWithBalance | null>(null);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [showInactive, setShowInactive] = useState(false);
  const [form] = Form.useForm();

  // Mutation hooks
  const createAccountMutation = useCreateAccount();

  // Fetch accounts and balances from API
  const { data: accounts = [], isLoading: accountsLoading } = useAccounts(activeCompany?.id);
  const { data: balances = [], isLoading: balancesLoading } = useAccountBalances(
    activeCompany?.id,
    currentFiscalYear ? {
      startDate: dayjs(currentFiscalYear.startDate),
      endDate: dayjs(currentFiscalYear.endDate),
    } : undefined
  );

  const isLoading = accountsLoading || balancesLoading;

  // Combine accounts with balances and filter
  const tableData = useMemo(() => {
    const combined = accounts.map(acc => {
      const balance = balances.find(b => b.id === acc.id);
      return { ...acc, balance: balance?.netChange ?? 0 };
    });

    return combined
      .filter(acc => showInactive || acc.isActive)
      .filter(acc =>
        searchText === '' ||
        acc.name.toLowerCase().includes(searchText.toLowerCase()) ||
        acc.accountNumber.includes(searchText)
      )
      .sort((a, b) => a.accountNumber.localeCompare(b.accountNumber));
  }, [accounts, balances, searchText, showInactive]);

  // Calculate totals for KPI cards
  const kpiData = useMemo(() => {
    const data = accounts.map(acc => {
      const balance = balances.find(b => b.id === acc.id);
      return { ...acc, balance: balance?.netChange ?? 0 };
    });

    return {
      assets: data.filter(a => a.type === 'asset').reduce((sum, a) => sum + a.balance, 0),
      liabilities: data.filter(a => ['liability', 'equity'].includes(a.type)).reduce((sum, a) => sum + Math.abs(a.balance), 0),
      revenue: data.filter(a => a.type === 'revenue').reduce((sum, a) => sum + Math.abs(a.balance), 0),
      expenses: data.filter(a => ['cogs', 'expense', 'personnel', 'financial'].includes(a.type)).reduce((sum, a) => sum + a.balance, 0),
    };
  }, [accounts, balances]);

  const handleRowClick = (record: AccountWithBalance) => {
    setSelectedAccount(record);
    setIsEditMode(false);
    setIsDrawerOpen(true);
  };

  const handleCreateAccount = () => {
    setSelectedAccount(null);
    form.resetFields();
    setIsEditMode(true);
    setIsDrawerOpen(true);
  };

  const handleEditAccount = () => {
    if (selectedAccount) {
      form.setFieldsValue(selectedAccount);
      setIsEditMode(true);
    }
  };

  const handleCloseDrawer = () => {
    setIsDrawerOpen(false);
    setIsEditMode(false);
    setSelectedAccount(null);
  };

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

      if (!activeCompany) {
        message.error('Ingen virksomhed valgt');
        return;
      }

      if (selectedAccount) {
        // TODO: Backend does not yet have an updateAccount mutation.
        // For now, show a message indicating this is not yet supported.
        message.warning('Redigering af konti er endnu ikke understottet i backend');
      } else {
        // Create new account
        await createAccountMutation.mutateAsync({
          companyId: activeCompany.id,
          accountNumber: values.accountNumber,
          name: values.name,
          accountType: values.type,
          description: values.description,
          vatCodeId: values.vatCode,
        });
        message.success('Konto oprettet');
      }

      handleCloseDrawer();
    } catch (error) {
      if (error instanceof Error) {
        message.error(`Fejl: ${error.message}`);
      }
    }
  };

  const columns: ColumnsType<AccountWithBalance> = [
    {
      title: 'Nr.',
      dataIndex: 'accountNumber',
      key: 'accountNumber',
      width: 100,
      render: (text) => <Text code>{text}</Text>,
      sorter: (a, b) => a.accountNumber.localeCompare(b.accountNumber),
    },
    {
      title: 'Navn',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Text strong>{text}</Text>
          {!record.isActive && <Tag color="default" bordered={false}>Inaktiv</Tag>}
        </Space>
      ),
      sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 150,
      filters: accountTypes.map(type => ({ text: getAccountTypeName(type), value: type })),
      onFilter: (value, record) => record.type === value,
      render: (type) => <Tag>{getAccountTypeName(type)}</Tag>,
    },
    {
      title: 'Moms',
      dataIndex: 'vatCode',
      key: 'vatCode',
      width: 100,
      render: (code) => code ? <Tag color="blue">{code}</Tag> : <Text type="secondary">-</Text>,
    },
    {
      title: 'Saldo',
      dataIndex: 'balance',
      key: 'balance',
      align: 'right',
      width: 150,
      render: (value) => (
        <Text
          strong
          style={{
            color: value >= 0 ? accountingColors.credit : accountingColors.debit,
          }}
        >
          {formatCurrency(value)}
        </Text>
      ),
      sorter: (a, b) => a.balance - b.balance,
    },
    {
      key: 'action',
      width: 50,
      render: (_, record) => (
        <Button
          type="text"
          icon={<MoreOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            handleRowClick(record);
          }}
        />
      ),
    },
  ];

  return (
    <div>
      <PageHeader
        title="Kontooversigt"
        subtitle={activeCompany?.name}
        breadcrumbs={[
          { title: 'Bogføring', path: '/bogforing' },
          { title: 'Kontooversigt' },
        ]}
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreateAccount}
          >
            Ny konto
          </Button>
        }
      />

      {/* KPI Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={12} sm={6}>
          <Card bordered={false} size="small" style={{ borderTop: `3px solid ${accountingColors.credit}` }}>
            <Statistic
              title="Aktiver"
              value={kpiData.assets}
              precision={0}
              valueStyle={{ color: accountingColors.credit }}
              formatter={(val) => formatCurrency(val as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card bordered={false} size="small" style={{ borderTop: `3px solid ${accountingColors.debit}` }}>
            <Statistic
              title="Passiver"
              value={kpiData.liabilities}
              precision={0}
              valueStyle={{ color: accountingColors.debit }}
              formatter={(val) => formatCurrency(val as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card bordered={false} size="small" style={{ borderTop: `3px solid ${accountingColors.credit}` }}>
            <Statistic
              title="Omsætning"
              value={kpiData.revenue}
              precision={0}
              valueStyle={{ color: accountingColors.credit }}
              formatter={(val) => formatCurrency(val as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card bordered={false} size="small" style={{ borderTop: `3px solid ${accountingColors.debit}` }}>
            <Statistic
              title="Omkostninger"
              value={kpiData.expenses}
              precision={0}
              valueStyle={{ color: accountingColors.debit }}
              formatter={(val) => formatCurrency(val as number)}
            />
          </Card>
        </Col>
      </Row>

      <Card
        bordered={false}
        bodyStyle={{ padding: 0 }}
        title={
          <Input
            prefix={<SearchOutlined className="text-gray-400" />}
            placeholder="Søg på navn eller nummer..."
            style={{ width: 300 }}
            allowClear
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
        }
        extra={
          <Space>
            <Space>
              <Text type="secondary" style={{ fontSize: 13 }}>Vis inaktive</Text>
              <Switch size="small" checked={showInactive} onChange={setShowInactive} />
            </Space>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={tableData}
          rowKey="id"
          loading={isLoading}
          pagination={{ pageSize: 50, showSizeChanger: true }}
          size="middle"
          onRow={(record) => ({
            onClick: () => handleRowClick(record),
            style: { cursor: 'pointer' },
          })}
        />
      </Card>

      {/* Details/Edit Drawer */}
      <Drawer
        title={
          isEditMode
            ? (selectedAccount ? 'Rediger konto' : 'Ny konto')
            : (
              <Space>
                {selectedAccount?.name}
                <Tag>{selectedAccount?.accountNumber}</Tag>
              </Space>
            )
        }
        width={500}
        open={isDrawerOpen}
        onClose={handleCloseDrawer}
        extra={
          !isEditMode && selectedAccount && (
            <Button type="primary" icon={<EditOutlined />} onClick={handleEditAccount}>
              Rediger
            </Button>
          )
        }
        footer={
          isEditMode && (
            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button onClick={() => isEditMode && selectedAccount ? setIsEditMode(false) : handleCloseDrawer()}>
                  Annuller
                </Button>
                <Button type="primary" onClick={handleSubmit}>
                  Gem konto
                </Button>
              </Space>
            </div>
          )
        }
      >
        {isEditMode ? (
          <Form form={form} layout="vertical">
             <Row gutter={16}>
               <Col span={12}>
                <Form.Item
                  name="accountNumber"
                  label="Kontonummer"
                  rules={[
                    { required: true, message: 'Påkrævet' },
                    { pattern: /^\d{4}$/, message: 'Skal være 4 cifre' },
                  ]}
                >
                  <Input maxLength={4} placeholder="1234" />
                </Form.Item>
               </Col>
               <Col span={12}>
                <Form.Item
                  name="type"
                  label="Kontotype"
                  rules={[{ required: true, message: 'Påkrævet' }]}
                >
                  <Select options={accountTypes.map(t => ({ label: getAccountTypeName(t), value: t }))} />
                </Form.Item>
               </Col>
             </Row>

            <Form.Item
              name="name"
              label="Kontonavn"
              rules={[{ required: true, message: 'Påkrævet' }]}
            >
              <Input placeholder="F.eks. Salg af varer" />
            </Form.Item>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="vatCode" label="Momskode">
                  <Select
                    allowClear
                    placeholder="Vælg..."
                    options={[
                      { value: 'S25', label: 'S25 - Udgående (Salg)' },
                      { value: 'K25', label: 'K25 - Indgående (Køb)' },
                      { value: 'E0', label: 'E0 - EU-salg' },
                      { value: 'U0', label: 'U0 - Eksport' },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="isActive" label="Status" valuePropName="checked" initialValue={true}>
                  <Switch checkedChildren="Aktiv" unCheckedChildren="Inaktiv" />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item name="description" label="Beskrivelse">
              <Input.TextArea rows={4} placeholder="Interne noter til denne konto..." />
            </Form.Item>
          </Form>
        ) : selectedAccount ? (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* Balance Summary */}
            <Card size="small" bordered={false} style={{ background: '#f5f5f5' }}>
              <Statistic
                title="Nuværende Saldo"
                value={selectedAccount.balance}
                precision={2}
                suffix="kr."
                valueStyle={{
                  color: selectedAccount.balance >= 0 ? accountingColors.credit : accountingColors.debit,
                  fontSize: 24,
                }}
              />
              <Text type="secondary" style={{ fontSize: 12 }}>
                Beregnet for indeværende regnskabsår
              </Text>
            </Card>

            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="Kontonummer">{selectedAccount.accountNumber}</Descriptions.Item>
              <Descriptions.Item label="Kontotype">{getAccountTypeName(selectedAccount.type)}</Descriptions.Item>
              <Descriptions.Item label="Moms">{selectedAccount.vatCode || <Text type="secondary">Ingen</Text>}</Descriptions.Item>
              <Descriptions.Item label="Status">
                {selectedAccount.isActive ? <Tag color="success">Aktiv</Tag> : <Tag color="default">Inaktiv</Tag>}
              </Descriptions.Item>
              {selectedAccount.description && (
                <Descriptions.Item label="Beskrivelse">
                  {selectedAccount.description}
                </Descriptions.Item>
              )}
            </Descriptions>

            <Divider orientation="left" plain><HistoryOutlined /> Seneste Bevægelser</Divider>
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <Text type="secondary">Ingen posteringer i den valgte periode.</Text>
              <br />
              <Button type="link" size="small" onClick={() => navigate('/kassekladde')}>Gå til kassekladde</Button>
            </div>

            <Divider plain />
            
            <Space direction="vertical" style={{ width: '100%' }}>
               <AlertInfo
                 message="Systemkonto"
                 description="Denne konto bruges automatisk af systemet til specifikke posteringer."
                 show={!!selectedAccount.isSystemAccount} 
               />
            </Space>

          </Space>
        ) : null}
      </Drawer>
    </div>
  );
}

// Helper component for alerts
function AlertInfo({ message, description, show }: { message: string, description: string, show: boolean }) {
  if (!show) return null;
  return (
    <div style={{ background: '#e6f7ff', border: '1px solid #91d5ff', padding: '8px 12px', borderRadius: 4 }}>
      <Space align="start">
        <InfoCircleOutlined style={{ color: '#1890ff', marginTop: 4 }} />
        <div>
          <Text strong style={{ color: '#1890ff' }}>{message}</Text>
          <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.65)' }}>{description}</div>
        </div>
      </Space>
    </div>
  );
}