import { useState } from 'react';
import {
  Typography,
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Button,
  Table,
  Statistic,
  Tag,
  Space,
  Divider,
  Alert,
  Modal,
  Descriptions,
  message,
} from 'antd';
import {
  DownloadOutlined,
  SendOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Pie } from '@ant-design/charts';
import dayjs from 'dayjs';
import { useCompany } from '@/hooks/useCompany';
import { formatCurrency, formatDate, formatPeriod } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';

const { Title, Text } = Typography;

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

const mockVATReport: VATBox[] = [
  {
    boxNumber: 1,
    nameDanish: 'Salgsmoms',
    nameEnglish: 'Output VAT',
    description: 'Moms af varer og ydelser solgt i Danmark (25%)',
    amount: 62500,
    basis: 250000,
  },
  {
    boxNumber: 2,
    nameDanish: 'Moms af varekøb i udlandet (EU)',
    nameEnglish: 'VAT on goods from EU',
    description: 'Erhvervelsesmoms ved køb af varer fra andre EU-lande',
    amount: 5000,
    basis: 20000,
  },
  {
    boxNumber: 3,
    nameDanish: 'Moms af ydelseskøb i udlandet',
    nameEnglish: 'VAT on services from abroad',
    description: 'Moms ved køb af ydelser fra udlandet med omvendt betalingspligt',
    amount: 2500,
    basis: 10000,
  },
  {
    boxNumber: 4,
    nameDanish: 'Købsmoms',
    nameEnglish: 'Input VAT',
    description: 'Fradragsberettiget moms af køb',
    amount: 35000,
    basis: 140000,
  },
  {
    boxNumber: 5,
    nameDanish: 'Olie- og flaskegasafgift',
    nameEnglish: 'Oil and gas duty',
    description: 'Godtgørelse af olie- og flaskegasafgift',
    amount: 0,
  },
  {
    boxNumber: 6,
    nameDanish: 'Elafgift',
    nameEnglish: 'Electricity duty',
    description: 'Godtgørelse af elafgift',
    amount: 1200,
  },
  {
    boxNumber: 7,
    nameDanish: 'Naturgas- og bygasafgift',
    nameEnglish: 'Natural gas duty',
    description: 'Godtgørelse af naturgas- og bygasafgift',
    amount: 0,
  },
  {
    boxNumber: 8,
    nameDanish: 'Kulafgift',
    nameEnglish: 'Coal duty',
    description: 'Godtgørelse af kulafgift',
    amount: 0,
  },
  {
    boxNumber: 9,
    nameDanish: 'CO2-afgift',
    nameEnglish: 'CO2 duty',
    description: 'Godtgørelse af CO2-afgift',
    amount: 300,
  },
];

// Historical submissions
const mockSubmissions = [
  {
    id: '1',
    period: '2024-10',
    submittedAt: '2024-11-28',
    status: 'accepted',
    netVAT: 28500,
    referenceNumber: 'SKAT-2024-123456',
  },
  {
    id: '2',
    period: '2024-07',
    submittedAt: '2024-08-30',
    status: 'accepted',
    netVAT: 32100,
    referenceNumber: 'SKAT-2024-789012',
  },
  {
    id: '3',
    period: '2024-04',
    submittedAt: '2024-05-29',
    status: 'accepted',
    netVAT: -5600,
    referenceNumber: 'SKAT-2024-345678',
  },
];

export default function Momsindberetning() {
  const { company } = useCompany();
  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 totals
  const outputVAT = mockVATReport
    .filter((box) => [1, 2, 3].includes(box.boxNumber))
    .reduce((sum, box) => sum + box.amount, 0);

  const inputVAT = mockVATReport
    .filter((box) => box.boxNumber === 4)
    .reduce((sum, box) => sum + box.amount, 0);

  const energyDuties = mockVATReport
    .filter((box) => [5, 6, 7, 8, 9].includes(box.boxNumber))
    .reduce((sum, box) => sum + box.amount, 0);

  const netVAT = outputVAT - inputVAT - energyDuties;

  // Pie chart config
  const pieData = [
    { type: 'Salgsmoms', value: mockVATReport[0].amount },
    { type: 'EU-moms', value: mockVATReport[1].amount + mockVATReport[2].amount },
    { type: 'Købsmoms (fradrag)', value: inputVAT },
    { type: 'Energiafgifter (fradrag)', value: energyDuties },
  ];

  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>
        );
      },
    },
  ];

  const handleSubmit = () => {
    Modal.confirm({
      title: 'Indsend momsangivelse',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>Du er ved at indsende momsangivelse for:</p>
          <p>
            <Text strong>Periode:</Text> {formatPeriod(selectedPeriod.toDate())}
          </p>
          <p>
            <Text strong>Moms til betaling:</Text>{' '}
            <Text
              style={{
                color: netVAT >= 0 ? accountingColors.debit : accountingColors.credit,
              }}
            >
              {formatCurrency(Math.abs(netVAT))}
              {netVAT < 0 ? ' (tilgode)' : ''}
            </Text>
          </p>
          <Alert
            message="Denne handling kan ikke fortrydes"
            type="warning"
            showIcon
            style={{ marginTop: 16 }}
          />
        </div>
      ),
      okText: 'Indsend til SKAT',
      cancelText: 'Annuller',
      onOk: () => {
        message.success('Momsangivelse indsendt til SKAT');
      },
    });
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'accepted':
        return (
          <Tag color="green" icon={<CheckCircleOutlined />}>
            Godkendt
          </Tag>
        );
      case 'pending':
        return (
          <Tag color="blue" icon={<ClockCircleOutlined />}>
            Afventer
          </Tag>
        );
      case 'rejected':
        return (
          <Tag color="red" icon={<ExclamationCircleOutlined />}>
            Afvist
          </Tag>
        );
      default:
        return <Tag>{status}</Tag>;
    }
  };

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Momsindberetning
          </Title>
          <Text type="secondary">{company?.name}</Text>
        </div>
        <Space>
          <Button icon={<DownloadOutlined />}>Eksporter</Button>
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={() => setIsPreviewOpen(true)}
          >
            Forhåndsvis
          </Button>
        </Space>
      </div>

      {/* 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: 'Månedlig' },
              { 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>
        </Space>
      </Card>

      {/* Summary Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} lg={6}>
          <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={6}>
          <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={6}>
          <Card size="small">
            <Statistic
              title="Energiafgifter (fradrag)"
              value={energyDuties}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.credit }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <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">
            <Table
              dataSource={mockVATReport}
              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>
              )}
            />
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card title="Fordeling" size="small" style={{ marginBottom: 16 }}>
            <Pie {...pieConfig} />
          </Card>

          <Card title="Tidligere indberetninger" size="small">
            {mockSubmissions.map((sub) => (
              <div
                key={sub.id}
                style={{
                  padding: '8px 0',
                  borderBottom: '1px solid #f0f0f0',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}
                >
                  <div>
                    <Text strong>
                      {dayjs(sub.period, 'YYYY-MM').format('MMMM YYYY')}
                    </Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      Indsendt {formatDate(sub.submittedAt)}
                    </Text>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    {getStatusTag(sub.status)}
                    <br />
                    <Text
                      className="tabular-nums"
                      style={{
                        color:
                          sub.netVAT >= 0
                            ? accountingColors.debit
                            : accountingColors.credit,
                      }}
                    >
                      {formatCurrency(sub.netVAT)}
                    </Text>
                  </div>
                </div>
              </div>
            ))}
          </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="submit"
            type="primary"
            icon={<SendOutlined />}
            onClick={() => {
              setIsPreviewOpen(false);
              handleSubmit();
            }}
          >
            Indsend til SKAT
          </Button>,
        ]}
      >
        <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 />

        <Table
          dataSource={mockVATReport}
          columns={[
            { dataIndex: 'boxNumber', title: 'Rubrik', width: 80 },
            { dataIndex: 'nameDanish', title: 'Felt' },
            {
              dataIndex: 'amount',
              title: 'Beløb',
              align: 'right',
              render: (v) => 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>
  );
}
