import { useState, useEffect, useCallback, useRef } from 'react';
import {
  Form,
  Input,
  InputNumber,
  Button,
  Slider,
  Card,
  Row,
  Col,
  Typography,
  Divider,
  message,
  Spin,
  AutoComplete,
  Switch,
} from 'antd';
import { SaveOutlined, PrinterOutlined, SearchOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { MapSettings, GeocodeSearchResult } from '@/types/api';

const { Text } = Typography;

export default function MapSettingsPage() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [citySearch, setCitySearch] = useState('');
  const [cityOptions, setCityOptions] = useState<{ value: string; label: React.ReactNode; result: GeocodeSearchResult }[]>([]);
  const [citySearching, setCitySearching] = useState(false);
  const cityTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const printRef = useRef<HTMLDivElement>(null);

  // Watch all form values so the walk sheet preview updates live
  const watched = Form.useWatch(undefined, form) as Record<string, string | undefined> | undefined;

  const fetchSettings = useCallback(async () => {
    try {
      const { data } = await api.get<MapSettings>('/map/settings');
      form.setFieldsValue({
        publicMapEnabled: data.publicMapEnabled ?? true,
        publicShowLocations: data.publicShowLocations ?? true,
        publicShowSupportLevels: data.publicShowSupportLevels ?? true,
        publicShowCuts: data.publicShowCuts ?? true,
        publicShowEvents: data.publicShowEvents ?? true,
        publicShowAddresses: data.publicShowAddresses ?? true,
        publicShowSignInfo: data.publicShowSignInfo ?? true,
        latitude: data.latitude ? parseFloat(data.latitude) : 45.4215,
        longitude: data.longitude ? parseFloat(data.longitude) : -75.6972,
        zoom: data.zoom ?? 12,
        walkSheetTitle: data.walkSheetTitle,
        walkSheetSubtitle: data.walkSheetSubtitle,
        walkSheetFooter: data.walkSheetFooter,
        qrCode1Url: data.qrCode1Url,
        qrCode1Label: data.qrCode1Label,
        qrCode2Url: data.qrCode2Url,
        qrCode2Label: data.qrCode2Label,
        qrCode3Url: data.qrCode3Url,
        qrCode3Label: data.qrCode3Label,
      });
    } catch {
      message.error('Failed to load map settings');
    } finally {
      setLoading(false);
    }
  }, [form]);

  useEffect(() => {
    fetchSettings();
  }, [fetchSettings]);

  const handleCitySearch = useCallback((value: string) => {
    setCitySearch(value);
    clearTimeout(cityTimerRef.current);
    if (value.length < 2) {
      setCityOptions([]);
      return;
    }
    cityTimerRef.current = setTimeout(async () => {
      setCitySearching(true);
      try {
        const { data } = await api.get<GeocodeSearchResult[]>('/map/geocoding/search', {
          params: { q: value, limit: 5 },
        });
        setCityOptions(data.map((r) => ({
          value: r.displayName,
          label: (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 300 }}>
                {r.displayName}
              </span>
              <span style={{ color: '#888', fontSize: 11, marginLeft: 8, flexShrink: 0 }}>{r.type}</span>
            </div>
          ),
          result: r,
        })));
      } catch {
        setCityOptions([]);
      } finally {
        setCitySearching(false);
      }
    }, 400);
  }, []);

  const handleCitySelect = useCallback((_value: string, option: { result: GeocodeSearchResult }) => {
    form.setFieldsValue({
      latitude: option.result.latitude,
      longitude: option.result.longitude,
      zoom: 12,
    });
    setCitySearch('');
    setCityOptions([]);
    message.success('Coordinates auto-filled. Fine-tune below.');
  }, [form]);

  useEffect(() => {
    return () => clearTimeout(cityTimerRef.current);
  }, []);

  const handleSave = async (values: Record<string, unknown>) => {
    setSaving(true);
    try {
      await api.put('/map/settings', values);
      message.success('Map settings saved');
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: { message?: string } } } })
          ?.response?.data?.error?.message || 'Failed to save settings';
      message.error(msg);
    } finally {
      setSaving(false);
    }
  };

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

  useEffect(() => {
    setPageHeader({ title: 'Map Settings' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

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

  // QR codes from live form values
  const qrCodes = [
    { url: watched?.qrCode1Url, label: watched?.qrCode1Label },
    { url: watched?.qrCode2Url, label: watched?.qrCode2Label },
    { url: watched?.qrCode3Url, label: watched?.qrCode3Label },
  ].filter((qr) => qr.url);

  return (
    <>
      <style>{`
        @media print {
          body * { visibility: hidden !important; }
          .walk-sheet-print, .walk-sheet-print * { visibility: visible !important; }
          .walk-sheet-print {
            position: fixed !important;
            left: 0 !important;
            top: 0 !important;
            width: 8.5in !important;
            height: 11in !important;
            padding: 0.4in 0.5in !important;
            background: white !important;
            color: black !important;
            box-sizing: border-box !important;
          }
          @page { size: letter; margin: 0; }
          .walk-sheet-print img { print-color-adjust: exact; -webkit-print-color-adjust: exact; }
        }
      `}</style>

      <Row gutter={24}>
        {/* Left column: Settings form */}
        <Col xs={24} lg={10}>
          <Form form={form} onFinish={handleSave} layout="vertical">
            <div style={{ display: 'flex', gap: 12, marginBottom: 24 }}>
              <Button
                type="primary"
                icon={<SaveOutlined />}
                loading={saving}
                htmlType="submit"
                size="large"
              >
                Save Settings
              </Button>
              <Button
                icon={<PrinterOutlined />}
                onClick={() => window.print()}
                size="large"
              >
                Print Walk Sheet
              </Button>
            </div>

            <Card title="Public Map Visibility" style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <Text strong>Enable Public Map</Text>
                  <br />
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    When disabled, the public-facing map at /map will show an unavailable message.
                  </Text>
                </div>
                <Form.Item name="publicMapEnabled" valuePropName="checked" noStyle>
                  <Switch />
                </Form.Item>
              </div>
            </Card>

            <Card title="Public Map Layer Visibility" style={{ marginBottom: 24 }}>
              <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
                Control which data layers are visible on the public map. Support levels and sign info are stripped server-side for security.
              </Text>
              {[
                { name: 'publicShowLocations', label: 'Show Location Markers', desc: 'Display location dots on the public map' },
                { name: 'publicShowSupportLevels', label: 'Show Support Levels', desc: 'Color markers by support level (stripped from API when off)' },
                { name: 'publicShowCuts', label: 'Show Cut Boundaries', desc: 'Display cut polygon overlays on the map' },
                { name: 'publicShowEvents', label: 'Show Events', desc: 'Display Gancio event markers on the map' },
                { name: 'publicShowAddresses', label: 'Show Addresses in Popups', desc: 'Display address text when clicking markers' },
                { name: 'publicShowSignInfo', label: 'Show Sign Info', desc: 'Display sign/sign-size data in popups (stripped from API when off)' },
              ].map(({ name, label, desc }) => (
                <div key={name} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                  <div>
                    <Text strong>{label}</Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: 12 }}>{desc}</Text>
                  </div>
                  <Form.Item name={name} valuePropName="checked" noStyle>
                    <Switch />
                  </Form.Item>
                </div>
              ))}
            </Card>

            <Card title="Map Center & Zoom" style={{ marginBottom: 24 }}>
              <div style={{ marginBottom: 16 }}>
                <AutoComplete
                  value={citySearch}
                  options={cityOptions}
                  onSearch={handleCitySearch}
                  onSelect={handleCitySelect as any}
                  placeholder="Search for a city to auto-fill coordinates..."
                  style={{ width: '100%' }}
                  suffixIcon={citySearching ? <Spin size="small" /> : <SearchOutlined />}
                />
                <Text type="secondary" style={{ fontSize: 12, marginTop: 4, display: 'block' }}>
                  Search for a city to auto-fill coordinates. Fine-tune below.
                </Text>
              </div>
              <Row gutter={16}>
                <Col xs={24} sm={8}>
                  <Form.Item name="latitude" label="Latitude" rules={[{ required: true }]}>
                    <InputNumber style={{ width: '100%' }} step={0.0001} min={-90} max={90} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="longitude" label="Longitude" rules={[{ required: true }]}>
                    <InputNumber style={{ width: '100%' }} step={0.0001} min={-180} max={180} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="zoom" label="Zoom Level">
                    <Slider min={2} max={19} />
                  </Form.Item>
                </Col>
              </Row>
              <Text type="secondary">
                Set the default center point and zoom level for the public map view.
              </Text>
            </Card>

            <Card title="Walk Sheet Configuration" style={{ marginBottom: 24 }}>
              <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                Configure headers and footers for printed walk sheets. Changes preview live on the right.
              </Text>
              <Form.Item name="walkSheetTitle" label="Title">
                <Input placeholder="Walk Sheet Title" />
              </Form.Item>
              <Form.Item name="walkSheetSubtitle" label="Subtitle">
                <Input placeholder="Walk Sheet Subtitle" />
              </Form.Item>
              <Form.Item name="walkSheetFooter" label="Footer">
                <Input.TextArea rows={2} placeholder="Footer text for walk sheets" />
              </Form.Item>

              <Divider orientation="left" plain>QR Codes</Divider>

              {[1, 2, 3].map((i) => (
                <Row gutter={12} key={i}>
                  <Col xs={24} sm={16}>
                    <Form.Item name={`qrCode${i}Url`} label={`QR Code ${i} URL`}>
                      <Input placeholder="https://..." />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={8}>
                    <Form.Item name={`qrCode${i}Label`} label="Label">
                      <Input placeholder={`QR ${i} Label`} />
                    </Form.Item>
                  </Col>
                </Row>
              ))}
            </Card>

          </Form>
        </Col>

        {/* Right column: Live walk sheet preview */}
        <Col xs={24} lg={14}>
          <Card
            title="Walk Sheet Preview"
            extra={
              <Button
                size="small"
                icon={<PrinterOutlined />}
                onClick={() => window.print()}
              >
                Print
              </Button>
            }
            style={{ marginBottom: 24 }}
            styles={{ body: { padding: 0, maxHeight: 'calc(100vh - 200px)', overflow: 'auto' } }}
          >
            <div
              ref={printRef}
              className="walk-sheet-print"
              style={{
                background: '#fff',
                color: '#000',
                padding: 32,
                maxWidth: '8.5in',
                margin: '0 auto',
                fontFamily: 'Arial, Helvetica, sans-serif',
                fontSize: 11,
              }}
            >
              {/* Header */}
              <div style={{ borderBottom: '2px solid #000', paddingBottom: 6, marginBottom: 10 }}>
                <div style={{ fontSize: 18, fontWeight: 700, textAlign: 'center' }}>
                  {watched?.walkSheetTitle || 'Walk Sheet'}
                </div>
                {watched?.walkSheetSubtitle && (
                  <div style={{ fontSize: 12, textAlign: 'center', color: '#333', marginTop: 2 }}>
                    {watched.walkSheetSubtitle}
                  </div>
                )}
              </div>

              {/* QR Codes */}
              {qrCodes.length > 0 && (
                <div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginBottom: 10 }}>
                  {qrCodes.map((qr, i) => (
                    <div key={i} style={{ textAlign: 'center' }}>
                      <img
                        src={`/api/qr?text=${encodeURIComponent(qr.url!)}&size=200`}
                        alt={qr.label || `QR Code ${i + 1}`}
                        style={{ width: 80, height: 80 }}
                      />
                      {qr.label && (
                        <div style={{ fontSize: 9, marginTop: 2 }}>{qr.label}</div>
                      )}
                    </div>
                  ))}
                </div>
              )}

              {/* Contact entry blocks */}
              {[1, 2].map((blockNum) => (
                <div key={blockNum} style={{ marginBottom: 6 }}>
                  {blockNum > 1 && (
                    <div style={{ borderTop: '1px dashed #999', marginBottom: 8 }} />
                  )}
                  <FormRow left="First Name" right="Last Name" />
                  <FormRow left="Email" right="Phone" />
                  <FormRow left="Address" right="Unit Number" />
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 6 }}>
                    <div>
                      <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>Support Level</div>
                      <div style={{ display: 'flex', gap: 8 }}>
                        {[1, 2, 3, 4].map((n) => (
                          <span key={n} style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>
                            <Circle /><span style={{ fontSize: 10 }}>{n}</span>
                          </span>
                        ))}
                      </div>
                    </div>
                    <div>
                      <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>Sign Request</div>
                      <div style={{ display: 'flex', gap: 8 }}>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>
                          <Circle /><span style={{ fontSize: 10 }}>Y</span>
                        </span>
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>
                          <Circle /><span style={{ fontSize: 10 }}>N</span>
                        </span>
                      </div>
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 6 }}>
                    <div>
                      <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>Sign Size</div>
                      <div style={{ display: 'flex', gap: 8 }}>
                        {['R', 'L', 'U'].map((s) => (
                          <span key={s} style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>
                            <Circle /><span style={{ fontSize: 10 }}>{s}</span>
                          </span>
                        ))}
                      </div>
                    </div>
                    <div>
                      <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>Visited Date</div>
                      <div style={{ borderBottom: '1px solid #999', height: 18 }} />
                    </div>
                  </div>
                </div>
              ))}

              {/* Notes */}
              <div style={{ marginTop: 8 }}>
                <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>Notes &amp; Comments</div>
                <div
                  style={{
                    border: '1px solid #999',
                    borderRadius: 3,
                    minHeight: 80,
                  }}
                />
              </div>

              {/* Footer */}
              {watched?.walkSheetFooter && (
                <div style={{ marginTop: 10, textAlign: 'center', fontSize: 9, color: '#666' }}>
                  {watched.walkSheetFooter}
                </div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </>
  );
}

function FormRow({ left, right }: { left: string; right: string }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 6 }}>
      <div>
        <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>{left}</div>
        <div style={{ borderBottom: '1px solid #999', height: 18 }} />
      </div>
      <div>
        <div style={{ fontSize: 9, color: '#666', marginBottom: 3 }}>{right}</div>
        <div style={{ borderBottom: '1px solid #999', height: 18 }} />
      </div>
    </div>
  );
}

function Circle() {
  return (
    <div
      style={{
        width: 13,
        height: 13,
        borderRadius: '50%',
        border: '1.5px solid #333',
        flexShrink: 0,
        display: 'inline-block',
      }}
    />
  );
}
