import { Row, Col, Card, Statistic, Typography, Space, Tag, Progress } from 'antd';
import {
  BankOutlined,
  RiseOutlined,
  FallOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import { Line, Pie, Column } from '@ant-design/charts';
import { useCompany } from '@/hooks/useCompany';
import { formatCurrency, formatDate } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';

const { Title, Text } = Typography;

// Mock data - will be replaced with API calls
const mockMetrics = {
  cashPosition: 1234567.89,
  cashChange: 0.12,
  accountsReceivable: 456789.12,
  arChange: -0.05,
  accountsPayable: 234567.89,
  apChange: 0.08,
  monthlyRevenue: 789012.34,
  revenueChange: 0.15,
  monthlyExpenses: 567890.12,
  expenseChange: 0.03,
  vatLiability: 123456.78,
  unreconciledCount: 23,
  pendingInvoices: 12,
  overdueInvoices: 3,
};

const mockCashFlowData = [
  { month: 'Jan', inflow: 120000, outflow: 80000, balance: 40000 },
  { month: 'Feb', inflow: 150000, outflow: 90000, balance: 60000 },
  { month: 'Mar', inflow: 130000, outflow: 85000, balance: 45000 },
  { month: 'Apr', inflow: 160000, outflow: 95000, balance: 65000 },
  { month: 'Maj', inflow: 140000, outflow: 100000, balance: 40000 },
  { month: 'Jun', inflow: 180000, outflow: 110000, balance: 70000 },
];

const mockExpenseBreakdown = [
  { category: 'Personale', value: 45 },
  { category: 'Lokaler', value: 20 },
  { category: 'IT & Software', value: 15 },
  { category: 'Marketing', value: 10 },
  { category: 'Andet', value: 10 },
];

const mockRecentTransactions = [
  { id: '1', date: '2025-01-15', description: 'Faktura #1234', amount: 12500, type: 'income' },
  { id: '2', date: '2025-01-14', description: 'Husleje januar', amount: -15000, type: 'expense' },
  { id: '3', date: '2025-01-13', description: 'Faktura #1233', amount: 8750, type: 'income' },
  { id: '4', date: '2025-01-12', description: 'Telefon abonnement', amount: -499, type: 'expense' },
  { id: '5', date: '2025-01-11', description: 'Faktura #1232', amount: 25000, type: 'income' },
];

export default function Dashboard() {
  const { company } = useCompany();

  const cashFlowConfig = {
    data: mockCashFlowData,
    xField: 'month',
    yField: 'balance',
    smooth: true,
    color: accountingColors.balance,
    point: { size: 4, shape: 'circle' },
    area: { style: { fillOpacity: 0.1 } },
    yAxis: {
      label: {
        formatter: (v: string) => `${parseInt(v) / 1000}k`,
      },
    },
    height: 200,
  };

  const expenseConfig = {
    data: mockExpenseBreakdown,
    angleField: 'value',
    colorField: 'category',
    radius: 0.8,
    innerRadius: 0.6,
    label: {
      type: 'outer',
      formatter: (datum: { category: string; value: number }) =>
        `${datum.category}: ${datum.value}%`,
    },
    legend: {
      position: 'right' as const,
    },
    height: 200,
  };

  const revenueExpenseConfig = {
    data: mockCashFlowData.flatMap((d) => [
      { month: d.month, type: 'Indtaegter', value: d.inflow },
      { month: d.month, type: 'Udgifter', value: d.outflow },
    ]),
    isGroup: true,
    xField: 'month',
    yField: 'value',
    seriesField: 'type',
    color: [accountingColors.credit, accountingColors.debit],
    yAxis: {
      label: {
        formatter: (v: string) => `${parseInt(v) / 1000}k`,
      },
    },
    height: 200,
  };

  return (
    <div>
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <Title level={4} style={{ margin: 0 }}>
          Dashboard
        </Title>
        <Text type="secondary">
          {company?.name} - {formatDate(new Date().toISOString(), 'MMMM YYYY')}
        </Text>
      </div>

      {/* KPI Cards */}
      <Row gutter={[16, 16]}>
        {/* Cash Position */}
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="Likviditet"
              value={mockMetrics.cashPosition}
              precision={2}
              prefix={<BankOutlined />}
              suffix="kr."
              formatter={(value) => formatCurrency(value as number)}
            />
            <div style={{ marginTop: 8 }}>
              <Tag
                color={mockMetrics.cashChange >= 0 ? 'green' : 'red'}
                icon={mockMetrics.cashChange >= 0 ? <RiseOutlined /> : <FallOutlined />}
              >
                {mockMetrics.cashChange >= 0 ? '+' : ''}
                {(mockMetrics.cashChange * 100).toFixed(1)}% denne maaned
              </Tag>
            </div>
          </Card>
        </Col>

        {/* Accounts Receivable */}
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="Tilgodehavender"
              value={mockMetrics.accountsReceivable}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.credit }}
              formatter={(value) => formatCurrency(value as number)}
            />
            <div style={{ marginTop: 8 }}>
              <Space size={4}>
                <Tag color="blue">{mockMetrics.pendingInvoices} afventer</Tag>
                {mockMetrics.overdueInvoices > 0 && (
                  <Tag color="red" icon={<WarningOutlined />}>
                    {mockMetrics.overdueInvoices} forfaldne
                  </Tag>
                )}
              </Space>
            </div>
          </Card>
        </Col>

        {/* Accounts Payable */}
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="Kreditorer"
              value={mockMetrics.accountsPayable}
              precision={2}
              suffix="kr."
              valueStyle={{ color: accountingColors.debit }}
              formatter={(value) => formatCurrency(value as number)}
            />
            <div style={{ marginTop: 8 }}>
              <Tag color={mockMetrics.apChange >= 0 ? 'orange' : 'green'}>
                {mockMetrics.apChange >= 0 ? '+' : ''}
                {(mockMetrics.apChange * 100).toFixed(1)}% denne maaned
              </Tag>
            </div>
          </Card>
        </Col>

        {/* VAT Liability */}
        <Col xs={24} sm={12} lg={6}>
          <Card size="small">
            <Statistic
              title="Moms til betaling"
              value={mockMetrics.vatLiability}
              precision={2}
              suffix="kr."
              formatter={(value) => formatCurrency(value as number)}
            />
            <div style={{ marginTop: 8 }}>
              <Tag color="blue">Naeste frist: 1. marts</Tag>
            </div>
          </Card>
        </Col>
      </Row>

      {/* Charts Row */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* Cash Flow Chart */}
        <Col xs={24} lg={12}>
          <Card title="Pengestroemme" size="small">
            <Line {...cashFlowConfig} />
          </Card>
        </Col>

        {/* Revenue vs Expenses */}
        <Col xs={24} lg={12}>
          <Card title="Indtaegter vs. Udgifter" size="small">
            <Column {...revenueExpenseConfig} />
          </Card>
        </Col>
      </Row>

      {/* Bottom Row */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* Expense Breakdown */}
        <Col xs={24} lg={8}>
          <Card title="Udgiftsfordeling" size="small">
            <Pie {...expenseConfig} />
          </Card>
        </Col>

        {/* Reconciliation Status */}
        <Col xs={24} lg={8}>
          <Card title="Afstemningsstatus" size="small">
            <div style={{ padding: '16px 0' }}>
              <Statistic
                title="Uafstemte transaktioner"
                value={mockMetrics.unreconciledCount}
                prefix={<FileTextOutlined />}
              />
              <Progress
                percent={75}
                status="active"
                strokeColor={accountingColors.balance}
                style={{ marginTop: 16 }}
              />
              <Text type="secondary">75% afstemt denne maaned</Text>
            </div>
          </Card>
        </Col>

        {/* Recent Transactions */}
        <Col xs={24} lg={8}>
          <Card
            title="Seneste transaktioner"
            size="small"
            bodyStyle={{ padding: 0 }}
          >
            <div style={{ maxHeight: 240, overflow: 'auto' }}>
              {mockRecentTransactions.map((tx) => (
                <div
                  key={tx.id}
                  style={{
                    padding: '8px 16px',
                    borderBottom: '1px solid #f0f0f0',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}
                >
                  <div>
                    <Text style={{ display: 'block' }}>{tx.description}</Text>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {formatDate(tx.date)}
                    </Text>
                  </div>
                  <Text
                    strong
                    className="tabular-nums"
                    style={{
                      color: tx.amount >= 0 ? accountingColors.credit : accountingColors.debit,
                    }}
                  >
                    {formatCurrency(tx.amount, { showSign: true })}
                  </Text>
                </div>
              ))}
            </div>
          </Card>
        </Col>
      </Row>

      {/* Quick Actions */}
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        <Col span={24}>
          <Card title="Hurtige handlinger" size="small">
            <Row gutter={[16, 16]}>
              <Col>
                <Space>
                  <CheckCircleOutlined style={{ color: accountingColors.credit }} />
                  <Text>23 transaktioner klar til afstemning</Text>
                </Space>
              </Col>
              <Col>
                <Space>
                  <ClockCircleOutlined style={{ color: accountingColors.warning }} />
                  <Text>Momsindberetning forfalder om 14 dage</Text>
                </Space>
              </Col>
              <Col>
                <Space>
                  <WarningOutlined style={{ color: accountingColors.debit }} />
                  <Text>3 fakturaer er forfaldne</Text>
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>
    </div>
  );
}
