import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Drawer, Typography, Button, Select, Statistic, Space, Divider, List, Grid, Alert,
  Modal, Input, App,
} from 'antd';
import {
  HistoryOutlined,
  LogoutOutlined,
  PlayCircleOutlined,
  AimOutlined,
  StopOutlined,
  ClockCircleOutlined,
  CloseOutlined,
  QrcodeOutlined,
  CopyOutlined,
  CheckOutlined,
} from '@ant-design/icons';
import SessionTimer from './SessionTimer';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import type { MyAssignment, MyCanvassStats } from '@/types/canvass';
import type { PublicCut } from '@/types/api';

interface VolunteerMapDrawerProps {
  open: boolean;
  onClose: () => void;
  drawerBodyRef?: React.RefObject<HTMLDivElement | null>;
  cuts: PublicCut[];
  onStartSession: (cutId: string, shiftId?: string) => void;
  sessionActive?: boolean;
  sessionCutName?: string;
  sessionStartedAt?: string;
  onEndSession?: () => void;
  endingSession?: boolean;
  activeCutId?: string;
  activeShiftId?: string;
  isAdmin?: boolean;
}

export default function VolunteerMapDrawer({
  open,
  onClose,
  drawerBodyRef,
  cuts,
  onStartSession,
  sessionActive = false,
  sessionCutName,
  sessionStartedAt,
  onEndSession,
  endingSession = false,
  activeCutId,
  activeShiftId,
  isAdmin = false,
}: VolunteerMapDrawerProps) {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const { user, logout } = useAuthStore();
  const [stats, setStats] = useState<MyCanvassStats | null>(null);
  const [assignments, setAssignments] = useState<MyAssignment[]>([]);
  const [freeCutId, setFreeCutId] = useState<string | null>(null);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  // QR invite modal state
  const [qrModalOpen, setQrModalOpen] = useState(false);
  const [inviteUrl, setInviteUrl] = useState<string | null>(null);
  const [generatingInvite, setGeneratingInvite] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (!open) return;
    // Load stats and assignments when drawer opens
    api.get('/map/canvass/my/stats').then(({ data }) => setStats(data)).catch(() => {});
    api.get('/map/canvass/my/assignments').then(({ data }) => setAssignments(data)).catch(() => {});
  }, [open]);

  const handleLogout = async () => {
    await logout();
    navigate('/login', { replace: true });
  };

  const handleGenerateInvite = async () => {
    setGeneratingInvite(true);
    try {
      const { data } = await api.post('/volunteer-invite/generate', {
        cutId: activeCutId || undefined,
        shiftId: activeShiftId || undefined,
      });
      // Build the join URL using current origin
      const joinUrl = `${window.location.origin}/join?token=${data.token}`;
      setInviteUrl(joinUrl);
      setQrModalOpen(true);
    } catch {
      message.error('Failed to generate invite link');
    } finally {
      setGeneratingInvite(false);
    }
  };

  const handleCopyUrl = async () => {
    if (!inviteUrl) return;
    try {
      await navigator.clipboard.writeText(inviteUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      message.error('Failed to copy');
    }
  };

  // Build QR code image URL using existing /api/qr endpoint
  const qrImageUrl = inviteUrl
    ? `/api/qr?text=${encodeURIComponent(inviteUrl)}&size=280`
    : null;

  return (
    <>
      <Drawer
        placement="bottom"
        open={open}
        onClose={onClose}
        height="auto"
        closable={false}
        mask={false}
        maskClosable={false}
        zIndex={1150}
        styles={{
          wrapper: {
            bottom: 0, // Sits at bottom, footer will push up
          },
          body: {
            padding: isMobile ? '12px' : '16px',
            maxHeight: '60vh',
            overflowY: 'auto',
          },
          header: { display: 'none' },
        }}
      >
        <div ref={drawerBodyRef} style={{ width: '100%' }}>
          {/* Header with drag handle and close button */}
          <div style={{ position: 'relative', marginBottom: 16 }}>
            {/* Drag handle at top center */}
            <div
              style={{
                width: 40,
                height: 4,
                background: 'rgba(255,255,255,0.3)',
                borderRadius: 2,
                margin: '0 auto',
              }}
            />

            {/* Close button at top right */}
            <Button
              type="text"
              icon={<CloseOutlined />}
              onClick={onClose}
              style={{
                position: 'absolute',
                top: -8,
                right: -8,
                color: 'rgba(255,255,255,0.6)',
              }}
              size="small"
            />
          </div>

          {/* Active session alert */}
        {sessionActive && sessionCutName && (
          <>
            <Alert
              message={
                <Space direction="vertical" size={0} style={{ width: '100%' }}>
                  <Typography.Text strong style={{ fontSize: 13 }}>
                    Active Session: {sessionCutName}
                  </Typography.Text>
                  {sessionStartedAt && (
                    <Space size={4}>
                      <ClockCircleOutlined style={{ fontSize: 12 }} />
                      <SessionTimer startedAt={sessionStartedAt} />
                    </Space>
                  )}
                </Space>
              }
              type="info"
              showIcon={false}
              action={
                onEndSession && (
                  <Button
                    danger
                    size="small"
                    icon={<StopOutlined />}
                    onClick={onEndSession}
                    loading={endingSession}
                  >
                    End
                  </Button>
                )
              }
              style={{ marginBottom: 16 }}
            />
            <Divider style={{ margin: '0 0 16px 0' }} />
          </>
        )}

        <Typography.Text strong style={{ fontSize: 16, display: 'block', marginBottom: 4 }}>
          {user?.name || user?.email || 'Volunteer'}
        </Typography.Text>
        <Typography.Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 16 }}>
          {user?.email}
        </Typography.Text>

        {/* Mini stats */}
        {stats && (
          <Space size="large" style={{ marginBottom: 16 }}>
            <Statistic title="Today" value={stats.todayVisits} valueStyle={{ fontSize: 20 }} />
            <Statistic title="Total" value={stats.totalVisits} valueStyle={{ fontSize: 20 }} />
          </Space>
        )}

        <Divider style={{ margin: '8px 0' }} />

        {/* Assignments (hidden when session active) */}
        {!sessionActive && assignments.length > 0 && (
          <>
            <Typography.Text strong style={{ display: 'block', marginBottom: 8, fontSize: 13 }}>
              My Assignments
            </Typography.Text>
            <List
              size="small"
              dataSource={assignments}
              style={{ marginBottom: 12, maxHeight: 200, overflowY: 'auto' }}
              renderItem={(a) => (
                <List.Item
                  style={{ padding: '6px 0' }}
                  actions={[
                    <Button
                      key="start"
                      type="primary"
                      size="small"
                      icon={<PlayCircleOutlined />}
                      onClick={() => { onStartSession(a.cutId, a.shiftId); onClose(); }}
                    >
                      Start
                    </Button>,
                  ]}
                >
                  <List.Item.Meta
                    title={<span style={{ fontSize: 13 }}>{a.cutName}</span>}
                    description={
                      <span style={{ fontSize: 11 }}>
                        {a.shiftTitle} &middot; {Math.round(a.completionPercentage)}%
                      </span>
                    }
                  />
                </List.Item>
              )}
            />
            <Divider style={{ margin: '8px 0' }} />
          </>
        )}

        {/* Free session — pick a cut (hidden when session active) */}
        {!sessionActive && (
          <>
            <Typography.Text strong style={{ display: 'block', marginBottom: 8, fontSize: 13 }}>
              Start Session (Any Cut)
            </Typography.Text>
            <Space.Compact style={{ width: '100%', marginBottom: 16 }}>
              <Select
                placeholder="Select a cut..."
                style={{ flex: 1 }}
                value={freeCutId}
                onChange={setFreeCutId}
                options={cuts.map((c) => ({ label: c.name, value: c.id }))}
                allowClear
              />
              <Button
                type="primary"
                icon={<AimOutlined />}
                disabled={!freeCutId}
                onClick={() => { if (freeCutId) { onStartSession(freeCutId); onClose(); } }}
              >
                Go
              </Button>
            </Space.Compact>
          </>
        )}

        {/* Navigation links */}
        <Button
          type="text"
          icon={<HistoryOutlined />}
          block
          style={{ textAlign: 'left', marginBottom: 4 }}
          onClick={() => { navigate('/volunteer/activity'); onClose(); }}
        >
          My Activity
        </Button>

        {/* Admin: Invite Volunteer button */}
        {isAdmin && (
          <Button
            type="text"
            icon={<QrcodeOutlined />}
            block
            style={{ textAlign: 'left', marginBottom: 4 }}
            onClick={handleGenerateInvite}
            loading={generatingInvite}
          >
            Invite Volunteer
          </Button>
        )}

        <div style={{ flex: 1 }} />

        <Divider style={{ margin: '8px 0' }} />
        <Button
          type="text"
          danger
          icon={<LogoutOutlined />}
          block
          style={{ textAlign: 'left' }}
          onClick={handleLogout}
        >
          Logout
        </Button>
        </div>
      </Drawer>

      {/* QR Code Invite Modal */}
      <Modal
        open={qrModalOpen}
        onCancel={() => { setQrModalOpen(false); setInviteUrl(null); setCopied(false); }}
        footer={null}
        title="Invite Volunteer"
        centered
        width={340}
        zIndex={1200}
      >
        <div style={{ textAlign: 'center', padding: '8px 0' }}>
          <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 16, fontSize: 13 }}>
            Show this QR code to a new volunteer. They'll scan it with their phone to get instant access.
          </Typography.Text>

          {qrImageUrl && (
            <div style={{ marginBottom: 16 }}>
              <img
                src={qrImageUrl}
                alt="Invite QR Code"
                style={{
                  width: 280,
                  height: 280,
                  borderRadius: 8,
                  background: '#fff',
                  padding: 8,
                }}
              />
            </div>
          )}

          <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 11 }}>
            Or copy this link to send via text:
          </Typography.Text>

          <Input.Search
            value={inviteUrl || ''}
            readOnly
            enterButton={
              <Button icon={copied ? <CheckOutlined /> : <CopyOutlined />} type={copied ? 'default' : 'primary'}>
                {copied ? 'Copied' : 'Copy'}
              </Button>
            }
            onSearch={handleCopyUrl}
            style={{ marginBottom: 8 }}
            size="small"
          />

          <Typography.Text type="secondary" style={{ display: 'block', fontSize: 11, marginTop: 8 }}>
            Link expires in 30 minutes. Access lasts 24 hours.
          </Typography.Text>
        </div>
      </Modal>
    </>
  );
}
