import { useEffect, useState } from 'react';
import { Button, Typography, Spin, App } from 'antd';
import { PrinterOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { MapSettings } from '@/types/api';

const { Title, Text } = Typography;

// Use relative URL — VITE_API_URL is a Docker-internal hostname the browser cannot resolve
const API_BASE = '';

export default function WalkSheetPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();
  const [settings, setSettings] = useState<MapSettings | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setPageHeader({
      title: 'Walk Sheet',
      actions: (
        <Button icon={<PrinterOutlined />} onClick={() => window.print()}>
          Print
        </Button>
      ),
    });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  useEffect(() => {
    api.get('/map/settings')
      .then(({ data }) => setSettings(data))
      .catch(() => message.error('Failed to load settings'))
      .finally(() => setLoading(false));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

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

  const qrCodes = [
    { url: settings?.qrCode1Url, label: settings?.qrCode1Label },
    { url: settings?.qrCode2Url, label: settings?.qrCode2Label },
    { url: settings?.qrCode3Url, label: settings?.qrCode3Label },
  ].filter((q) => q.url);

  const rows = Array.from({ length: 12 }, (_, i) => i);

  return (
    <>
      <style>{`
        @media print {
          body * { visibility: hidden; }
          .walk-sheet-print, .walk-sheet-print * { visibility: visible; }
          .walk-sheet-print {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            font-size: 11px;
          }
          .walk-sheet-print .no-print { display: none !important; }
        }
        .walk-sheet-print table {
          width: 100%;
          border-collapse: collapse;
        }
        .walk-sheet-print th,
        .walk-sheet-print td {
          border: 1px solid #555;
          padding: 4px 6px;
          text-align: left;
          font-size: 11px;
        }
        .walk-sheet-print th {
          background: rgba(255,255,255,0.05);
          font-weight: 600;
        }
        .support-circle {
          display: inline-block;
          width: 16px;
          height: 16px;
          border: 1.5px solid rgba(255,255,255,0.4);
          border-radius: 50%;
          text-align: center;
          line-height: 14px;
          font-size: 9px;
          margin-right: 2px;
        }
      `}</style>

      <div className="walk-sheet-print">
        {/* Header */}
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          <Title level={3} style={{ marginBottom: 2 }}>
            {settings?.walkSheetTitle || 'Walk Sheet'}
          </Title>
          {settings?.walkSheetSubtitle && (
            <Text type="secondary" style={{ fontSize: 14 }}>{settings.walkSheetSubtitle}</Text>
          )}
        </div>

        {/* QR Codes */}
        {qrCodes.length > 0 && (
          <div style={{ display: 'flex', justifyContent: 'center', gap: 24, marginBottom: 16 }}>
            {qrCodes.map((qr, idx) => (
              <div key={idx} style={{ textAlign: 'center' }}>
                <img
                  src={`${API_BASE}/api/qr?text=${encodeURIComponent(qr.url!)}&size=100`}
                  alt={qr.label || 'QR'}
                  style={{ width: 80, height: 80 }}
                />
                {qr.label && (
                  <div style={{ fontSize: 10, marginTop: 2 }}>
                    <Text type="secondary">{qr.label}</Text>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Volunteer info line */}
        <div style={{ display: 'flex', gap: 16, marginBottom: 12 }}>
          <div style={{ flex: 1 }}>
            <Text strong>Volunteer: </Text>
            <span style={{ borderBottom: '1px solid rgba(255,255,255,0.3)', display: 'inline-block', width: 200 }}>&nbsp;</span>
          </div>
          <div>
            <Text strong>Date: </Text>
            <span style={{ borderBottom: '1px solid rgba(255,255,255,0.3)', display: 'inline-block', width: 120 }}>&nbsp;</span>
          </div>
          <div>
            <Text strong>Area/Cut: </Text>
            <span style={{ borderBottom: '1px solid rgba(255,255,255,0.3)', display: 'inline-block', width: 120 }}>&nbsp;</span>
          </div>
        </div>

        {/* Contact table */}
        <table>
          <thead>
            <tr>
              <th style={{ width: 20 }}>#</th>
              <th>Name</th>
              <th>Address / Unit</th>
              <th>Email</th>
              <th>Phone</th>
              <th style={{ width: 70 }}>Support</th>
              <th style={{ width: 50 }}>Sign</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((i) => (
              <tr key={i}>
                <td style={{ textAlign: 'center' }}>{i + 1}</td>
                <td style={{ height: 28 }}>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td style={{ textAlign: 'center' }}>
                  <span className="support-circle">1</span>
                  <span className="support-circle">2</span>
                  <span className="support-circle">3</span>
                  <span className="support-circle">4</span>
                </td>
                <td style={{ textAlign: 'center' }}>
                  <span className="support-circle">R</span>
                  <span className="support-circle">L</span>
                </td>
                <td>&nbsp;</td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Footer */}
        {settings?.walkSheetFooter && (
          <div style={{ marginTop: 16, fontSize: 11, textAlign: 'center' }}>
            <Text type="secondary">{settings.walkSheetFooter}</Text>
          </div>
        )}
      </div>
    </>
  );
}
