import { useState, useMemo } from 'react';
import {
  Typography,
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Button,
  Table,
  Statistic,
  Tag,
  Space,
  Divider,
  Alert,
  Modal,
  Descriptions,
  Empty,
  Skeleton,
} from 'antd';
import {
  DownloadOutlined,
  SendOutlined,
} from '@ant-design/icons';
import { Pie } from '@ant-design/charts';
import dayjs from 'dayjs';
import { useCompany } from '@/hooks/useCompany';
import { useCompanyStore } from '@/stores/companyStore';
import { useVatReport } from '@/api/queries/vatQueries';
import { formatCurrency, formatPeriod } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import { DemoDataDisclaimer } from '@/components/shared/DemoDataDisclaimer';
import { PageHeader } from '@/components/shared/PageHeader';

const { Text } = Typography;

// Danish VAT boxes (Rubrikker) - mapped from backend VatReport
interface VATBox {
  boxNumber: number;
  nameDanish: string;
  nameEnglish: string;
  description: string;
  amount: number;
  basis?: number;
}

export default function Momsindberetning() {
  const { company } = useCompany();
  const { activeCompany } = useCompanyStore();
  const [selectedPeriod, setSelectedPeriod] = useState<dayjs.Dayjs>(
    dayjs().subtract(1, 'month').startOf('month')
  );
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [periodType, setPeriodType] = useState<'monthly' | 'quarterly'>('quarterly');

  // Calculate period dates based on selection
  const periodStart = useMemo(() => {
    if (periodType === 'quarterly') {
      return selectedPeriod.startOf('quarter').format('YYYY-MM-DD');
    }
    return selectedPeriod.startOf('month').format('YYYY-MM-DD');
  }, [selectedPeriod, periodType]);

  const periodEnd = useMemo(() => {
    if (periodType === 'quarterly') {
      return selectedPeriod.endOf('quarter').format('YYYY-MM-DD');
    }
    return selectedPeriod.endOf('month').format('YYYY-MM-DD');
  }, [selectedPeriod, periodType]);

  // Fetch VAT report from backend
  const { data: vatReport, isLoading, error } = useVatReport(
    activeCompany?.id,
    periodStart,
    periodEnd
  );

  // Map backend VatReport to UI's rubrik display
  const vatBoxes: VATBox[] = useMemo(() => {
    if (!vatReport) return [];
    return [
      {
        boxNumber: 1,
        nameDanish: 'Salgsmoms',
        nameEnglish: 'Output VAT',
        description: 'Moms af varer og ydelser solgt i Danmark (25%)',
        amount: vatReport.boxA,
        basis: vatReport.basis1,
      },
      {
        boxNumber: 2,
        nameDanish: 'Moms af varekob i udlandet (EU)',
        nameEnglish: 'VAT on goods from EU',
        description: 'Erhvervelsesmoms ved kob af varer fra andre EU-lande',
        amount: vatReport.boxC,
        basis: vatReport.basis3,
      },
      {
        boxNumber: 3,
        nameDanish: 'Moms af ydelseskob i udlandet',
        nameEnglish: 'VAT on services from abroad',
        description: 'Moms ved kob af ydelser fra udlandet med omvendt betalingspligt',
        amount: vatReport.boxD,
        basis: vatReport.basis4,
      },
      {
        boxNumber: 4,
        nameDanish: 'Kobsmoms',
        nameEnglish: 'Input VAT',
        description: 'Fradragsberettiget moms af kob',
        amount: vatReport.boxB,
        basis: undefined, // Backend doesn't provide a specific basis for input VAT
      },
    ];
  }, [vatReport]);

  // Calculate totals from real data
  const outputVAT = vatReport?.totalOutputVat ?? 0;
  const inputVAT = vatReport?.totalInputVat ?? 0;
  const netVAT = vatReport?.netVat ?? 0;

  // Pie chart config
  const pieData = useMemo(() => {
    if (!vatReport) return [];
    return [
      { type: 'Salgsmoms', value: vatReport.boxA },
      { type: 'EU-moms', value: (vatReport.boxC || 0) + (vatReport.boxD || 0) },
      { type: 'Kobsmoms (fradrag)', value: inputVAT },
    ].filter(d => d.value > 0);
  }, [vatReport, inputVAT]);

  const pieConfig = {
    data: pieData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    innerRadius: 0.6,
    label: {
      type: 'outer',
      formatter: (datum: { type: string; value: number }) =>
        `${datum.type}: ${formatCurrency(datum.value)}`,
    },
    legend: {
      position: 'bottom' as const,
    },
    height: 250,
  };

  const columns = [
    {
      dataIndex: 'boxNumber',
      title: 'Rubrik',
      width: 80,
      render: (value: number) => <Text strong>{value}</Text>,
    },
    {
      dataIndex: 'nameDanish',
      title: 'Felt',
      render: (value: string, record: VATBox) => (
        <div>
          <Text strong>{value}</Text>
          <br />
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.description}
          </Text>
        </div>
      ),
    },
    {
      dataIndex: 'basis',
      title: 'Grundlag',
      align: 'right' as const,
      width: 140,
      render: (value: number | undefined) =>
        value !== undefined ? (
          <span className="tabular-nums">{formatCurrency(value)}</span>
        ) : (
          '-'
        ),
    },
    {
      dataIndex: 'amount',
      title: 'Moms/Afgift',
      align: 'right' as const,
      width: 140,
      render: (value: number, record: VATBox) => {
        const isDeductible = record.boxNumber >= 4;
        return (
          <span
            className="tabular-nums"
            style={{
              color: isDeductible ? accountingColors.credit : accountingColors.debit,
              fontWeight: 'bold',
            }}
          >
            {isDeductible ? '-' : ''}
            {formatCurrency(value)}
          </span>
        );
      },
    },
  ];

  // Loading state
  if (isLoading) {
    return (
      <div>
        <PageHeader
          title="Momsindberetning"
          subtitle={company?.name}
          breadcrumbs={[{ title: 'Rapportering' }, { title: 'Momsindberetning' }]}
        />
        <Skeleton active paragraph={{ rows: 8 }} />
      </div>
    );
  }

  return (
    <div>
      <PageHeader
        title="Momsindberetning"
        subtitle={company?.name}
        breadcrumbs={[{ title: 'Rapportering' }, { title: 'Momsindberetning' }]}
        extra={
          <Space>
            <Button icon={<DownloadOutlined />}>Eksporter</Button>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={() => setIsPreviewOpen(true)}
              disabled={!vatReport}
            >
              Forhåndsvis
            </Button>
          </Space>
        }
      />

      {/* SKAT submission notice */}
      <Alert
        type="warning"
        message="Indberetning skal ske manuelt på skat.dk"
        description="Automatisk indberetning til SKAT er endnu ikke implementeret. Brug disse tal til at udfylde momsangivelsen på skat.dk manuelt."
        showIcon
        style={{ marginBottom: 16 }}
      />

      {/* Period Selection */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <Text>Periode:</Text>
          <Select
            value={periodType}
            onChange={setPeriodType}
            style={{ width: 120 }}
            options={[
              { value: 'monthly', label: 'Maanedlig' },
              { value: 'quarterly', label: 'Kvartalsvis' },
            ]}
          />
          <DatePicker
            picker={periodType === 'quarterly' ? 'quarter' : 'month'}
            value={selectedPeriod}
            onChange={(date) => date && setSelectedPeriod(date)}
            format={periodType === 'quarterly' ? '[Q]Q YYYY' : 'MMMM YYYY'}
          />
          <Tag color="blue">
            Frist: {dayjs(selectedPeriod).add(1, 'month').endOf('month').format('D. MMMM YYYY')}
          </Tag>
          {vatReport && (
            <Tag color="green">{vatReport.transactionCount} transaktioner</Tag>
          )}
        </Space>
      </Card>

      {/* Error state */}
      {error && (
        <Alert
          type="error"
          message="Fejl ved indlaesning af momsdata"
          description={error.message}
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {/* Summary Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} lg={8}>
          <Card size="small">
            <Statistic
              title="Udgående moms"
              value={outputVAT}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.debit }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8}>
          <Card size="small">
            <Statistic
              title="Indgående moms (fradrag)"
              value={inputVAT}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.credit }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8}>
          <Card size="small">
            <Statistic
              title={netVAT >= 0 ? 'Moms til betaling' : 'Moms til gode'}
              value={Math.abs(netVAT)}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color: netVAT >= 0 ? accountingColors.debit : accountingColors.credit,
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* Main Content */}
      <Row gutter={16}>
        <Col xs={24} lg={16}>
          <Card title="Momsangivelse - Rubrikker" size="small">
            {vatBoxes.length > 0 ? (
              <Table
                dataSource={vatBoxes}
                columns={columns}
                rowKey="boxNumber"
                pagination={false}
                size="small"
                summary={() => (
                  <Table.Summary fixed>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={0} colSpan={3}>
                        <Text strong>Moms til betaling / tilgode</Text>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align="right">
                        <Text
                          strong
                          className="tabular-nums"
                          style={{
                            fontSize: 16,
                            color:
                              netVAT >= 0 ? accountingColors.debit : accountingColors.credit,
                          }}
                        >
                          {netVAT >= 0 ? '' : '-'}
                          {formatCurrency(Math.abs(netVAT))}
                        </Text>
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                  </Table.Summary>
                )}
              />
            ) : (
              <Empty description="Ingen momsdata for den valgte periode" />
            )}
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card title="Fordeling" size="small" style={{ marginBottom: 16 }}>
            {pieData.length > 0 ? (
              <Pie {...pieConfig} />
            ) : (
              <Empty description="Ingen data at vise" style={{ height: 200 }} />
            )}
          </Card>

          <Card title="Tidligere indberetninger" size="small">
            <DemoDataDisclaimer message="Indberetningshistorik er endnu ikke tilgængelig" />
            <Text type="secondary">
              Tidligere indberetninger vil blive vist her nar SKAT-integration er implementeret.
            </Text>
          </Card>
        </Col>
      </Row>

      {/* Preview Modal */}
      <Modal
        title="Forhåndsvisning af momsangivelse"
        open={isPreviewOpen}
        onCancel={() => setIsPreviewOpen(false)}
        width={700}
        footer={[
          <Button key="cancel" onClick={() => setIsPreviewOpen(false)}>
            Luk
          </Button>,
          <Button key="export" icon={<DownloadOutlined />}>
            Download PDF
          </Button>,
          <Button
            key="skat-link"
            type="primary"
            icon={<SendOutlined />}
            onClick={() => {
              window.open('https://skat.dk', '_blank');
              setIsPreviewOpen(false);
            }}
          >
            Ga til skat.dk
          </Button>,
        ]}
      >
        <Alert
          type="info"
          message="Brug disse tal til at udfylde momsangivelsen på skat.dk"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Descriptions bordered column={1} size="small">
          <Descriptions.Item label="Virksomhed">{company?.name}</Descriptions.Item>
          <Descriptions.Item label="CVR">{company?.cvr}</Descriptions.Item>
          <Descriptions.Item label="Periode">
            {formatPeriod(selectedPeriod.toDate())}
          </Descriptions.Item>
          <Descriptions.Item label="Periodens afslutning">
            {selectedPeriod.endOf('month').format('D. MMMM YYYY')}
          </Descriptions.Item>
        </Descriptions>

        <Divider />

        {vatBoxes.length > 0 && (
          <Table
            dataSource={vatBoxes}
            columns={[
              { dataIndex: 'boxNumber', title: 'Rubrik', width: 80 },
              { dataIndex: 'nameDanish', title: 'Felt' },
              {
                dataIndex: 'amount',
                title: 'Belob',
                align: 'right',
                render: (v: number) => formatCurrency(v),
              },
            ]}
            rowKey="boxNumber"
            pagination={false}
            size="small"
          />
        )}

        <Divider />

        <div style={{ textAlign: 'right' }}>
          <Text strong style={{ fontSize: 18 }}>
            {netVAT >= 0 ? 'Moms til betaling: ' : 'Moms til gode: '}
            <span
              style={{
                color: netVAT >= 0 ? accountingColors.debit : accountingColors.credit,
              }}
            >
              {formatCurrency(Math.abs(netVAT))}
            </span>
          </Text>
        </div>
      </Modal>
    </div>
  );
}
