import { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate, useOutletContext } from 'react-router-dom';
import {
  Button,
  Typography,
  Spin,
  Space,
  Table,
  Tag,
  Row,
  Col,
  Card,
  Statistic,
  message,
} from 'antd';
import { PrinterOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { Cut, Location, Address, CutStatistics, SupportLevel } from '@/types/api';
import {
  SUPPORT_LEVEL_LABELS,
  SUPPORT_LEVEL_COLORS,
  CUT_CATEGORY_LABELS,
  CUT_CATEGORY_COLORS,
} from '@/types/api';

const { Title, Text } = Typography;

// Combined type for table display - Address with parent Location info
interface AddressWithLocation extends Address {
  locationAddress: string; // Building street address
}

export default function CutExportPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [cut, setCut] = useState<Cut | null>(null);
  const [addresses, setAddresses] = useState<AddressWithLocation[]>([]);
  const [stats, setStats] = useState<CutStatistics | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    (async () => {
      try {
        const [cutRes, locsRes, statsRes] = await Promise.all([
          api.get<Cut>(`/map/cuts/${id}`),
          api.get<Location[]>(`/map/cuts/${id}/locations`),
          api.get<CutStatistics>(`/map/cuts/${id}/statistics`),
        ]);
        setCut(cutRes.data);

        // Flatten locations with their addresses
        const flatAddresses: AddressWithLocation[] = [];
        for (const loc of locsRes.data) {
          if (loc.addresses && loc.addresses.length > 0) {
            for (const addr of loc.addresses) {
              flatAddresses.push({
                ...addr,
                locationAddress: loc.address,
              });
            }
          }
        }
        setAddresses(flatAddresses);

        setStats(statsRes.data);
      } catch {
        message.error('Failed to load cut data');
      } finally {
        setLoading(false);
      }
    })();
  }, [id]);

  const { setPageHeader } = useOutletContext<AppOutletContext>();

  const headerActions = useMemo(() => (
    <Space>
      <Button
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/app/map/cuts')}
      >
        Back to Cuts
      </Button>
      <Button
        type="primary"
        icon={<PrinterOutlined />}
        onClick={() => window.print()}
      >
        Print
      </Button>
    </Space>
  ), [navigate]);

  useEffect(() => {
    setPageHeader({ title: cut?.name || 'Cut Export', actions: headerActions });
    return () => setPageHeader(null);
  }, [setPageHeader, headerActions, cut?.name]);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!cut) {
    return <Text type="danger">Cut not found</Text>;
  }

  const now = dayjs().format('YYYY-MM-DD HH:mm');

  const withEmail = addresses.filter((a) => a.email).length;
  const withPhone = addresses.filter((a) => a.phone).length;

  const columns: ColumnsType<AddressWithLocation> = [
    {
      title: 'Name',
      key: 'name',
      render: (_: unknown, record: AddressWithLocation) =>
        [record.firstName, record.lastName].filter(Boolean).join(' ') || '--',
    },
    {
      title: 'Address',
      key: 'address',
      render: (_: unknown, record: AddressWithLocation) =>
        [record.locationAddress, record.unitNumber && `#${record.unitNumber}`].filter(Boolean).join(' ') || '--',
    },
    {
      title: 'Support',
      dataIndex: 'supportLevel',
      key: 'supportLevel',
      width: 120,
      render: (level: SupportLevel | null) =>
        level ? (
          <Tag color={SUPPORT_LEVEL_COLORS[level]}>{SUPPORT_LEVEL_LABELS[level]}</Tag>
        ) : (
          <Tag>None</Tag>
        ),
    },
    {
      title: 'Phone',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
      render: (val: string | null) => val || '--',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (val: string | null) => val || '--',
    },
    {
      title: 'Sign',
      key: 'sign',
      width: 80,
      render: (_: unknown, record: AddressWithLocation) =>
        record.sign
          ? `Yes${record.signSize ? ` (${record.signSize})` : ''}`
          : 'No',
    },
    {
      title: 'Notes',
      dataIndex: 'notes',
      key: 'notes',
      width: 150,
      ellipsis: true,
      render: (val: string | null) => val || '--',
    },
  ];

  return (
    <>
      <style>{`
        @media print {
          body * { visibility: hidden !important; }
          .cut-export-print, .cut-export-print * { visibility: visible !important; }
          .cut-export-print {
            position: fixed !important;
            left: 0 !important;
            top: 0 !important;
            width: 100% !important;
            padding: 0.4in !important;
            background: white !important;
            color: black !important;
            font-size: 10px !important;
          }
          .cut-export-print .ant-table { font-size: 9px !important; }
          .cut-export-print .ant-table-thead > tr > th {
            background: #f0f0f0 !important;
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
            padding: 4px 6px !important;
          }
          .cut-export-print .ant-table-tbody > tr > td { padding: 3px 6px !important; }
          .cut-export-print .ant-tag {
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
          }
          .cut-export-print .ant-card { box-shadow: none !important; border: 1px solid #ddd !important; }
          @page { size: letter landscape; margin: 0.25in; }
        }
      `}</style>

      {/* Printable content */}
      <div className="cut-export-print">
        {/* Report header */}
        <div style={{ marginBottom: 16 }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Title level={4} style={{ margin: 0 }}>{cut.name}</Title>
              <Space style={{ marginTop: 4 }}>
                {cut.category && (
                  <Tag color={CUT_CATEGORY_COLORS[cut.category]}>
                    {CUT_CATEGORY_LABELS[cut.category]}
                  </Tag>
                )}
                {cut.assignedTo && <Text type="secondary">Assigned to: {cut.assignedTo}</Text>}
              </Space>
            </Col>
            <Col>
              <Text type="secondary">Generated: {now}</Text>
            </Col>
          </Row>
        </div>

        {/* Stats grid */}
        {stats && (
          <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic title="Total" value={stats.total} />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic
                  title="Strong"
                  value={stats.byLevel.LEVEL_1 || 0}
                  valueStyle={{ color: SUPPORT_LEVEL_COLORS.LEVEL_1 }}
                />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic
                  title="Likely"
                  value={stats.byLevel.LEVEL_2 || 0}
                  valueStyle={{ color: SUPPORT_LEVEL_COLORS.LEVEL_2 }}
                />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic
                  title="Unsure"
                  value={stats.byLevel.LEVEL_3 || 0}
                  valueStyle={{ color: SUPPORT_LEVEL_COLORS.LEVEL_3 }}
                />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic
                  title="Oppose"
                  value={stats.byLevel.LEVEL_4 || 0}
                  valueStyle={{ color: SUPPORT_LEVEL_COLORS.LEVEL_4 }}
                />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic title="None" value={stats.byLevel.NONE || 0} />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic title="Signs" value={stats.withSign} />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic title="Email" value={withEmail} />
              </Card>
            </Col>
            <Col xs={8} sm={4}>
              <Card size="small">
                <Statistic title="Phone" value={withPhone} />
              </Card>
            </Col>
          </Row>
        )}

        {/* Address table */}
        <Table<AddressWithLocation>
          columns={columns}
          dataSource={addresses}
          rowKey="id"
          pagination={false}
          size="small"
          bordered
        />

        {/* Footer */}
        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <Text type="secondary" style={{ fontSize: 10 }}>
            Generated by Changemaker Lite &mdash; {now}
          </Text>
        </div>
      </div>
    </>
  );
}
