import { useState, useRef } from 'react';
import { Button, Badge, Drawer, Tooltip } from 'antd';
import {
  ArrowRightOutlined,
  NodeIndexOutlined,
  AimOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  PlusOutlined,
  SearchOutlined,
  EyeOutlined,
  InfoCircleOutlined,
  UpOutlined,
  DownOutlined,
  GlobalOutlined,
  BookOutlined,
} from '@ant-design/icons';
import type { PublicCut } from '@/types/api';
import CutOverlayControls from '@/components/map/CutOverlayControls';
import CanvassLegend from './CanvassLegend';
import AddressSearchOverlay from './AddressSearchOverlay';
import DocsSearchOverlay from './DocsSearchOverlay';
import { TILE_LAYERS } from '@/components/map/tileLayers';

interface BottomControlPanelProps {
  // Session controls
  sessionActive?: boolean;
  visitedCount: number;
  totalCount: number;
  routeVisible: boolean;
  gpsFollowing: boolean;
  fullscreen?: boolean;

  // Cut overlay
  cuts: PublicCut[];
  visibleCutIds: Set<string>;

  // Tile layer
  activeTileKey: string;
  onTileChange: (key: string) => void;

  // Handlers
  onNextDoor: () => void;
  onToggleRoute: () => void;
  onToggleGps: () => void;
  onToggleFullscreen?: () => void;
  onAddAtCenter?: () => void;
  onToggleCut: (id: string) => void;
  onSearchFlyTo: (lat: number, lng: number) => void;

  bottomOffset?: number;
}

export default function BottomControlPanel({
  sessionActive = false,
  visitedCount,
  totalCount,
  routeVisible,
  gpsFollowing,
  fullscreen,
  cuts,
  visibleCutIds,
  activeTileKey,
  onTileChange,
  onNextDoor,
  onToggleRoute,
  onToggleGps,
  onToggleFullscreen,
  onAddAtCenter,
  onToggleCut,
  onSearchFlyTo,
  bottomOffset = 56,
}: BottomControlPanelProps) {
  const [collapsed, setCollapsed] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const [showCuts, setShowCuts] = useState(false);
  const [showLegend, setShowLegend] = useState(false);
  const [showTiles, setShowTiles] = useState(false);
  const [showDocs, setShowDocs] = useState(false);
  const globeBtnRef = useRef<HTMLDivElement>(null);

  // Compact icon button with scale feedback
  const IconButton = ({
    icon,
    onClick,
    label,
    type = 'default',
    ghost,
    badge,
  }: {
    icon: React.ReactNode;
    onClick: () => void;
    label: string;
    type?: 'default' | 'primary';
    ghost?: boolean;
    badge?: string | number;
  }) => {
    const [pressed, setPressed] = useState(false);

    const button = (
      <Tooltip title={label} mouseEnterDelay={0.5}>
        <Button
          type={type}
          icon={icon}
          onClick={onClick}
          size="middle"
          ghost={ghost}
          aria-label={label}
          onTouchStart={() => setPressed(true)}
          onTouchEnd={() => setPressed(false)}
          onMouseDown={() => setPressed(true)}
          onMouseUp={() => setPressed(false)}
          onMouseLeave={() => setPressed(false)}
          style={{
            transform: pressed ? 'scale(0.92)' : 'scale(1)',
            transition: 'transform 0.08s ease',
            minWidth: 36,
            width: 36,
            height: 36,
            padding: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        />
      </Tooltip>
    );

    return badge ? (
      <Badge count={badge} size="small" offset={[-4, 4]} style={{ fontSize: 10 }}>
        {button}
      </Badge>
    ) : (
      button
    );
  };

  // When collapsed, show a small floating expand button
  if (collapsed) {
    return (
      <div
        style={{
          position: 'absolute',
          bottom: bottomOffset + 8,
          right: 12,
          zIndex: 1100,
        }}
      >
        <Button
          type="primary"
          icon={<UpOutlined />}
          onClick={() => setCollapsed(false)}
          size="small"
          shape="circle"
          aria-label="Show controls"
          style={{
            width: 36,
            height: 36,
            boxShadow: '0 2px 8px rgba(0,0,0,0.4)',
          }}
        />
      </div>
    );
  }

  return (
    <>
      {/* Single compact control bar */}
      <div
        style={{
          position: 'absolute',
          bottom: bottomOffset,
          left: 0,
          right: 0,
          zIndex: 1100,
          background: 'rgba(13, 27, 42, 0.98)',
          borderTop: '1px solid rgba(255,255,255,0.15)',
          backdropFilter: 'blur(12px)',
          WebkitBackdropFilter: 'blur(12px)',
          paddingBottom: 'env(safe-area-inset-bottom)',
          transition: 'all 0.12s ease',
        }}
      >
        <div
          style={{
            padding: '4px 8px',
            display: 'flex',
            alignItems: 'center',
            gap: 6,
            justifyContent: 'space-between',
            flexWrap: 'wrap',
          }}
        >
          {/* Left group: Collapse */}
          <div style={{ display: 'flex', gap: 4 }}>
            <IconButton
              icon={<DownOutlined />}
              onClick={() => setCollapsed(true)}
              label="Hide controls"
            />
          </div>

          {/* Center group: Session actions (if active) */}
          {sessionActive && (
            <div style={{ display: 'flex', gap: 4 }}>
              <IconButton
                icon={<ArrowRightOutlined />}
                onClick={onNextDoor}
                label="Next door"
                type="primary"
              />
              <IconButton
                icon={<NodeIndexOutlined />}
                onClick={onToggleRoute}
                label="Toggle route"
                type={routeVisible ? 'primary' : 'default'}
                ghost={routeVisible}
              />
            </div>
          )}

          {/* Center group: Utility buttons */}
          <div style={{ display: 'flex', gap: 4, flex: sessionActive ? 0 : 1, justifyContent: sessionActive ? 'flex-start' : 'center' }}>
            <div ref={globeBtnRef} style={{ display: 'inline-flex' }}>
              <IconButton
                icon={<GlobalOutlined />}
                onClick={() => { setShowTiles(!showTiles); setShowSearch(false); setShowCuts(false); setShowLegend(false); setShowDocs(false); }}
                label="Map tiles"
                type={showTiles ? 'primary' : 'default'}
              />
            </div>
            <IconButton
              icon={<SearchOutlined />}
              onClick={() => { setShowSearch(!showSearch); setShowTiles(false); setShowCuts(false); setShowLegend(false); setShowDocs(false); }}
              label="Search"
              type={showSearch ? 'primary' : 'default'}
            />
            {cuts.length > 0 && (
              <IconButton
                icon={<EyeOutlined />}
                onClick={() => { setShowCuts(!showCuts); setShowTiles(false); setShowSearch(false); setShowLegend(false); setShowDocs(false); }}
                label="Cuts"
                type={showCuts ? 'primary' : 'default'}
                badge={visibleCutIds.size > 0 ? visibleCutIds.size : undefined}
              />
            )}
            <IconButton
              icon={<InfoCircleOutlined />}
              onClick={() => { setShowLegend(!showLegend); setShowTiles(false); setShowSearch(false); setShowCuts(false); setShowDocs(false); }}
              label="Legend"
              type={showLegend ? 'primary' : 'default'}
            />
            <IconButton
              icon={<BookOutlined />}
              onClick={() => { setShowDocs(!showDocs); setShowTiles(false); setShowSearch(false); setShowCuts(false); setShowLegend(false); }}
              label="Docs"
              type={showDocs ? 'primary' : 'default'}
            />
            {onAddAtCenter && (
              <IconButton
                icon={<PlusOutlined />}
                onClick={onAddAtCenter}
                label="Add location"
              />
            )}
            {onToggleFullscreen && (
              <IconButton
                icon={fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                onClick={onToggleFullscreen}
                label={fullscreen ? 'Exit fullscreen' : 'Fullscreen'}
                type={fullscreen ? 'primary' : 'default'}
              />
            )}
          </div>

          {/* Right group: GPS + Badge */}
          <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
            <IconButton
              icon={<AimOutlined />}
              onClick={onToggleGps}
              label="GPS"
              type={gpsFollowing ? 'primary' : 'default'}
              ghost={gpsFollowing}
            />
            {sessionActive && (
              <Badge
                count={`${visitedCount}/${totalCount}`}
                style={{
                  backgroundColor: visitedCount === totalCount && totalCount > 0 ? '#27ae60' : '#3498db',
                  fontSize: 10,
                  height: 18,
                  lineHeight: '18px',
                  padding: '0 5px',
                  borderRadius: 9,
                }}
              />
            )}
          </div>
        </div>
      </div>

      {/* Floating panels */}

      {/* Tile layer popup - vertical stack above button */}
      {showTiles && (
        <>
          {/* Backdrop to close on tap */}
          <div
            onClick={() => setShowTiles(false)}
            style={{
              position: 'fixed',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              zIndex: 1089,
            }}
          />
          {/* Tile options - vertically stacked */}
          <div
            style={{
              position: 'absolute',
              bottom: bottomOffset + 44 + 8, // Just above control bar (44px bar height + 8px gap)
              left: globeBtnRef.current ? globeBtnRef.current.getBoundingClientRect().left : 8,
              zIndex: 1090,
              display: 'flex',
              flexDirection: 'column',
              gap: 4,
            }}
          >
            {TILE_LAYERS.map((layer) => (
              <button
                key={layer.key}
                onClick={() => {
                  onTileChange(layer.key);
                  setShowTiles(false);
                }}
                aria-label={layer.label}
                aria-pressed={activeTileKey === layer.key}
                style={{
                  width: 36,
                  height: 36,
                  border: activeTileKey === layer.key ? '2px solid #1890ff' : '1px solid rgba(255,255,255,0.3)',
                  borderRadius: 8,
                  background: activeTileKey === layer.key ? 'rgba(24, 144, 255, 0.25)' : 'rgba(13, 27, 42, 0.98)',
                  backdropFilter: 'blur(12px)',
                  color: activeTileKey === layer.key ? '#1890ff' : 'rgba(255,255,255,0.8)',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 16,
                  transition: 'all 0.08s',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                }}
              >
                <GlobalOutlined style={{ transform: layer.key === 'satellite' ? 'rotate(45deg)' : 'none' }} />
              </button>
            ))}
          </div>
        </>
      )}

      {/* Search drawer */}
      <Drawer
        placement="top"
        open={showSearch}
        onClose={() => setShowSearch(false)}
        height="auto"
        closable={false}
        maskClosable
        mask={false}
        zIndex={1090}
        styles={{
          body: { padding: '12px 16px', background: 'rgba(13, 27, 42, 0.98)' },
          wrapper: { top: 'env(safe-area-inset-top)' },
        }}
      >
        <AddressSearchOverlay
          onFlyTo={(lat, lng) => {
            onSearchFlyTo(lat, lng);
            setShowSearch(false);
          }}
          style={{ position: 'relative', top: 0, left: 0, right: 0 }}
        />
      </Drawer>

      {/* Cuts drawer */}
      <Drawer
        placement="top"
        open={showCuts}
        onClose={() => setShowCuts(false)}
        height="auto"
        closable={false}
        maskClosable
        mask={false}
        zIndex={1090}
        styles={{
          body: { padding: '12px 16px', background: 'rgba(13, 27, 42, 0.98)' },
          wrapper: { top: 'env(safe-area-inset-top)' },
        }}
      >
        <CutOverlayControls
          cuts={cuts}
          visibleCutIds={visibleCutIds}
          onToggleCut={onToggleCut}
          variant="public"
          style={{ position: 'relative', top: 0, left: 0 }}
        />
      </Drawer>

      {/* Legend drawer */}
      <Drawer
        placement="top"
        open={showLegend}
        onClose={() => setShowLegend(false)}
        height="auto"
        closable={false}
        maskClosable
        mask={false}
        zIndex={1090}
        styles={{
          body: { padding: '12px 16px', background: 'rgba(13, 27, 42, 0.98)' },
          wrapper: { top: 'env(safe-area-inset-top)' },
        }}
      >
        <CanvassLegend style={{ position: 'relative', top: 0, right: 0, maxWidth: '100%' }} />
      </Drawer>

      {/* Docs search drawer */}
      <Drawer
        placement="top"
        open={showDocs}
        onClose={() => setShowDocs(false)}
        height="auto"
        closable={false}
        maskClosable
        mask={false}
        zIndex={1090}
        styles={{
          body: { padding: '12px 16px', background: 'rgba(13, 27, 42, 0.98)' },
          wrapper: { top: 'env(safe-area-inset-top)' },
        }}
      >
        <DocsSearchOverlay />
      </Drawer>
    </>
  );
}
