import { useState } from 'react';
import {
  Typography,
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Table,
  Statistic,
  Tag,
  Space,
  Button,
  Descriptions,
  Collapse,
} from 'antd';
import {
  TeamOutlined,
  DownloadOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Column } from '@ant-design/charts';
import dayjs from 'dayjs';
import { useCompany } from '@/hooks/useCompany';
import { formatCurrency } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import type { Employee, PayrollEntry } from '@/types/accounting';

const { Title, Text } = Typography;

// Mock data
const mockEmployees: Employee[] = [
  {
    id: '1',
    companyId: '1',
    name: 'Anders Andersen',
    employeeNumber: 'EMP001',
    department: 'Salg',
    position: 'Salgschef',
    startDate: '2020-03-15',
    isActive: true,
  },
  {
    id: '2',
    companyId: '1',
    name: 'Bente Bentsen',
    employeeNumber: 'EMP002',
    department: 'Økonomi',
    position: 'Bogholder',
    startDate: '2021-06-01',
    isActive: true,
  },
  {
    id: '3',
    companyId: '1',
    name: 'Christian Christensen',
    employeeNumber: 'EMP003',
    department: 'IT',
    position: 'Udvikler',
    startDate: '2022-01-10',
    isActive: true,
  },
  {
    id: '4',
    companyId: '1',
    name: 'Dorthe Dahl',
    employeeNumber: 'EMP004',
    department: 'HR',
    position: 'HR Manager',
    startDate: '2019-08-20',
    isActive: true,
  },
];

const mockPayroll: PayrollEntry[] = [
  {
    id: '1',
    employeeId: '1',
    period: '2025-01',
    grossSalary: 45000,
    amBidrag: 3600,
    aSkat: 12500,
    atp: 99.65,
    pension: 4500,
    netSalary: 24300.35,
    otherDeductions: 0,
    status: 'approved',
  },
  {
    id: '2',
    employeeId: '2',
    period: '2025-01',
    grossSalary: 38000,
    amBidrag: 3040,
    aSkat: 9800,
    atp: 99.65,
    pension: 3800,
    netSalary: 21260.35,
    otherDeductions: 0,
    status: 'approved',
  },
  {
    id: '3',
    employeeId: '3',
    period: '2025-01',
    grossSalary: 42000,
    amBidrag: 3360,
    aSkat: 11200,
    atp: 99.65,
    pension: 4200,
    netSalary: 23140.35,
    otherDeductions: 0,
    status: 'approved',
  },
  {
    id: '4',
    employeeId: '4',
    period: '2025-01',
    grossSalary: 48000,
    amBidrag: 3840,
    aSkat: 13500,
    atp: 99.65,
    pension: 4800,
    netSalary: 25760.35,
    otherDeductions: 0,
    status: 'approved',
  },
];

// Monthly breakdown for chart
const mockMonthlyData = [
  { month: 'Aug 2024', grossTotal: 165000, netTotal: 91000 },
  { month: 'Sep 2024', grossTotal: 168000, netTotal: 92500 },
  { month: 'Okt 2024', grossTotal: 170000, netTotal: 93800 },
  { month: 'Nov 2024', grossTotal: 172000, netTotal: 94600 },
  { month: 'Dec 2024', grossTotal: 175000, netTotal: 96000 },
  { month: 'Jan 2025', grossTotal: 173000, netTotal: 94460 },
];

export default function Loenforstaelse() {
  const { company } = useCompany();
  const [selectedPeriod, setSelectedPeriod] = useState<dayjs.Dayjs>(dayjs().startOf('month'));
  const [selectedEmployee, setSelectedEmployee] = useState<string | null>(null);

  // Calculate totals
  const totalGross = mockPayroll.reduce((sum, p) => sum + p.grossSalary, 0);
  const totalAMBidrag = mockPayroll.reduce((sum, p) => sum + p.amBidrag, 0);
  const totalASkat = mockPayroll.reduce((sum, p) => sum + p.aSkat, 0);
  const totalATP = mockPayroll.reduce((sum, p) => sum + p.atp, 0);
  const totalPension = mockPayroll.reduce((sum, p) => sum + p.pension, 0);
  const totalNet = mockPayroll.reduce((sum, p) => sum + p.netSalary, 0);

  // Chart config
  const chartData = mockMonthlyData.flatMap((d) => [
    { month: d.month, type: 'Bruttoløn', value: d.grossTotal },
    { month: d.month, type: 'Nettoløn', value: d.netTotal },
  ]);

  const chartConfig = {
    data: chartData,
    isGroup: true,
    xField: 'month',
    yField: 'value',
    seriesField: 'type',
    color: [accountingColors.balance, accountingColors.credit],
    label: {
      position: 'top' as const,
      formatter: (datum: { value: number }) =>
        `${(datum.value / 1000).toFixed(0)}k`,
    },
    yAxis: {
      label: {
        formatter: (v: string) => `${parseInt(v) / 1000}k`,
      },
    },
    height: 250,
  };

  const payrollColumns = [
    {
      dataIndex: 'employeeId',
      title: 'Medarbejder',
      render: (id: string) => {
        const emp = mockEmployees.find((e) => e.id === id);
        return (
          <Space>
            <UserOutlined />
            <div>
              <Text strong>{emp?.name}</Text>
              <br />
              <Text type="secondary" style={{ fontSize: 12 }}>
                {emp?.position} • {emp?.department}
              </Text>
            </div>
          </Space>
        );
      },
    },
    {
      dataIndex: 'grossSalary',
      title: 'Bruttoløn',
      align: 'right' as const,
      render: (v: number) => <span className="tabular-nums">{formatCurrency(v)}</span>,
    },
    {
      dataIndex: 'amBidrag',
      title: 'AM-bidrag (8%)',
      align: 'right' as const,
      render: (v: number) => (
        <span className="tabular-nums" style={{ color: accountingColors.debit }}>
          -{formatCurrency(v)}
        </span>
      ),
    },
    {
      dataIndex: 'aSkat',
      title: 'A-skat',
      align: 'right' as const,
      render: (v: number) => (
        <span className="tabular-nums" style={{ color: accountingColors.debit }}>
          -{formatCurrency(v)}
        </span>
      ),
    },
    {
      dataIndex: 'atp',
      title: 'ATP',
      align: 'right' as const,
      render: (v: number) => (
        <span className="tabular-nums" style={{ color: accountingColors.debit }}>
          -{formatCurrency(v)}
        </span>
      ),
    },
    {
      dataIndex: 'pension',
      title: 'Pension',
      align: 'right' as const,
      render: (v: number) => (
        <span className="tabular-nums" style={{ color: accountingColors.debit }}>
          -{formatCurrency(v)}
        </span>
      ),
    },
    {
      dataIndex: 'netSalary',
      title: 'Nettoløn',
      align: 'right' as const,
      render: (v: number) => (
        <span
          className="tabular-nums"
          style={{ fontWeight: 'bold', color: accountingColors.credit }}
        >
          {formatCurrency(v)}
        </span>
      ),
    },
    {
      dataIndex: 'status',
      title: 'Status',
      width: 100,
      render: (status: string) =>
        status === 'approved' ? (
          <Tag color="green">Godkendt</Tag>
        ) : status === 'paid' ? (
          <Tag color="blue">Udbetalt</Tag>
        ) : (
          <Tag color="orange">Kladde</Tag>
        ),
    },
  ];

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Lønforståelse
          </Title>
          <Text type="secondary">{company?.name}</Text>
        </div>
        <Space>
          <Button icon={<DownloadOutlined />}>Eksporter lønsedler</Button>
        </Space>
      </div>

      {/* Period Selection */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <Text>Periode:</Text>
          <DatePicker
            picker="month"
            value={selectedPeriod}
            onChange={(date) => date && setSelectedPeriod(date)}
            format="MMMM YYYY"
          />
          <Select
            placeholder="Vælg medarbejder"
            style={{ width: 200 }}
            allowClear
            value={selectedEmployee}
            onChange={setSelectedEmployee}
            options={mockEmployees.map((emp) => ({
              value: emp.id,
              label: emp.name,
            }))}
          />
        </Space>
      </Card>

      {/* Summary Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="Medarbejdere"
              value={mockEmployees.length}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="Bruttoløn i alt"
              value={totalGross}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
            />
          </Card>
        </Col>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="AM-bidrag"
              value={totalAMBidrag}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.debit }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="A-skat"
              value={totalASkat}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.debit }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="ATP + Pension"
              value={totalATP + totalPension}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.debit }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={8} lg={4}>
          <Card size="small">
            <Statistic
              title="Nettoløn i alt"
              value={totalNet}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{ color: accountingColors.credit }}
            />
          </Card>
        </Col>
      </Row>

      {/* Main Content */}
      <Row gutter={16}>
        <Col xs={24} lg={16}>
          <Card title="Lønspecifikation" size="small">
            <Table
              dataSource={mockPayroll}
              columns={payrollColumns}
              rowKey="id"
              size="small"
              pagination={false}
              summary={() => (
                <Table.Summary fixed>
                  <Table.Summary.Row style={{ backgroundColor: '#fafafa' }}>
                    <Table.Summary.Cell index={0}>
                      <Text strong>I alt</Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align="right">
                      <Text strong className="tabular-nums">
                        {formatCurrency(totalGross)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={2} align="right">
                      <Text
                        strong
                        className="tabular-nums"
                        style={{ color: accountingColors.debit }}
                      >
                        -{formatCurrency(totalAMBidrag)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={3} align="right">
                      <Text
                        strong
                        className="tabular-nums"
                        style={{ color: accountingColors.debit }}
                      >
                        -{formatCurrency(totalASkat)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={4} align="right">
                      <Text
                        strong
                        className="tabular-nums"
                        style={{ color: accountingColors.debit }}
                      >
                        -{formatCurrency(totalATP)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={5} align="right">
                      <Text
                        strong
                        className="tabular-nums"
                        style={{ color: accountingColors.debit }}
                      >
                        -{formatCurrency(totalPension)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={6} align="right">
                      <Text
                        strong
                        className="tabular-nums"
                        style={{ color: accountingColors.credit }}
                      >
                        {formatCurrency(totalNet)}
                      </Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={7}></Table.Summary.Cell>
                  </Table.Summary.Row>
                </Table.Summary>
              )}
            />
          </Card>

          {/* Løn Forklaring */}
          <Card title="Sådan beregnes lønnen" size="small" style={{ marginTop: 16 }}>
            <Collapse
              items={[
                {
                  key: '1',
                  label: 'AM-bidrag (Arbejdsmarkedsbidrag)',
                  children: (
                    <div>
                      <Text>
                        AM-bidraget er på <Text strong>8%</Text> af bruttolønnen og trækkes
                        før A-skat beregnes.
                      </Text>
                      <br />
                      <Text type="secondary">
                        Eksempel: Bruttoløn 45.000 kr. × 8% = 3.600 kr.
                      </Text>
                    </div>
                  ),
                },
                {
                  key: '2',
                  label: 'A-skat',
                  children: (
                    <div>
                      <Text>
                        A-skat beregnes af (bruttoløn - AM-bidrag) efter medarbejderens
                        skattekort. Skatteprocenten afhænger af personfradrag og
                        kommuneskat.
                      </Text>
                    </div>
                  ),
                },
                {
                  key: '3',
                  label: 'ATP (Arbejdsmarkedets Tillægspension)',
                  children: (
                    <div>
                      <Text>
                        ATP-bidraget er pt. <Text strong>99,65 kr.</Text> pr. måned for
                        fuldtidsansatte. Arbejdsgiver betaler 2/3, lønmodtager betaler 1/3.
                      </Text>
                    </div>
                  ),
                },
                {
                  key: '4',
                  label: 'Pension',
                  children: (
                    <div>
                      <Text>
                        Pensionsbidraget afhænger af overenskomst eller individuel aftale.
                        Typisk mellem 8-17% af bruttolønnen, hvoraf arbejdsgiver ofte
                        betaler 2/3.
                      </Text>
                    </div>
                  ),
                },
              ]}
            />
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          {/* Trend Chart */}
          <Card title="Lønudvikling (6 måneder)" size="small" style={{ marginBottom: 16 }}>
            <Column {...chartConfig} />
          </Card>

          {/* Cost Breakdown */}
          <Card title="Lønomkostninger for arbejdsgiver" size="small">
            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">Ud over bruttolønnen betaler arbejdsgiver:</Text>
            </div>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="Feriepenge (12,5%)">
                {formatCurrency(totalGross * 0.125)}
              </Descriptions.Item>
              <Descriptions.Item label="ATP (arbejdsgiver 2/3)">
                {formatCurrency(totalATP * 2)}
              </Descriptions.Item>
              <Descriptions.Item label="Pension (arbejdsgiver)">
                {formatCurrency(totalPension * 2)}
              </Descriptions.Item>
              <Descriptions.Item label="AES/AUB bidrag (ca.)">
                {formatCurrency(mockEmployees.length * 450)}
              </Descriptions.Item>
            </Descriptions>
            <div
              style={{
                marginTop: 16,
                padding: '8px 16px',
                backgroundColor: '#f5f5f5',
                borderRadius: 4,
              }}
            >
              <Text strong>Total lønomkostning (estimat): </Text>
              <Text strong style={{ color: accountingColors.debit }}>
                {formatCurrency(
                  totalGross * 1.125 + totalATP * 2 + totalPension * 2 + mockEmployees.length * 450
                )}
              </Text>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
}
