import { useState, useEffect, useRef, useCallback } from 'react';
import {
  Typography, Button, Input, Card, Space, message, Result, Statistic,
  Row, Col, Divider, Spin,
} from 'antd';
import {
  ArrowLeftOutlined, CameraOutlined, KeyOutlined,
  CheckCircleOutlined, CloseCircleOutlined, WarningOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import { useParams, useNavigate } from 'react-router-dom';

const { Title, Text } = Typography;

interface ScanResult {
  type: 'success' | 'warning' | 'error';
  title: string;
  subtitle: string;
  ticket?: Record<string, unknown>;
}

export default function CheckInScannerPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [event, setEvent] = useState<Record<string, unknown> | null>(null);
  const [stats, setStats] = useState<{ totalTickets: number; checkedIn: number; remaining: number } | null>(null);
  const [scanResult, setScanResult] = useState<ScanResult | null>(null);
  const [manualCode, setManualCode] = useState('');
  const [manualEmail, setManualEmail] = useState('');
  const [processing, setProcessing] = useState(false);
  const [mode, setMode] = useState<'camera' | 'manual'>('manual');
  const scannerRef = useRef<unknown>(null);
  const scannerContainerRef = useRef<HTMLDivElement>(null);

  const fetchEvent = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get(`/ticketed-events/admin/${id}`);
      setEvent(data);
    } catch {
      message.error('Failed to load event');
    }
  }, [id]);

  const fetchStats = useCallback(async () => {
    if (!id) return;
    try {
      const { data } = await api.get(`/ticketed-events/checkin/event/${id}/stats`);
      setStats(data);
    } catch { /* silent */ }
  }, [id]);

  useEffect(() => {
    fetchEvent();
    fetchStats();
    const interval = setInterval(fetchStats, 5000); // Refresh stats every 5s
    return () => clearInterval(interval);
  }, [fetchEvent, fetchStats]);

  const handleQrScan = useCallback(async (decodedText: string) => {
    if (processing) return;
    setProcessing(true);
    setScanResult(null);

    try {
      // Extract token from URL or use raw text
      let token = decodedText;
      try {
        const url = new URL(decodedText);
        const t = url.searchParams.get('token');
        if (t) token = t;
      } catch { /* not a URL, use raw text */ }

      // Validate first
      const { data: validation } = await api.post('/ticketed-events/checkin/validate', { token });

      if (!validation.valid) {
        setScanResult({
          type: validation.error === 'Already checked in' ? 'warning' : 'error',
          title: validation.error,
          subtitle: validation.ticket
            ? `${validation.ticket.ticketCode} — ${validation.ticket.holderName || validation.ticket.holderEmail}`
            : '',
          ticket: validation.ticket,
        });
        setProcessing(false);
        return;
      }

      // Confirm check-in
      const { data: result } = await api.post('/ticketed-events/checkin/confirm', { token });
      setScanResult({
        type: 'success',
        title: 'Checked In!',
        subtitle: `${result.ticket.ticketCode} — ${result.ticket.holderName || result.ticket.holderEmail}`,
        ticket: result.ticket,
      });
      fetchStats();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Scan failed';
      setScanResult({ type: 'error', title: msg, subtitle: '' });
    } finally {
      setProcessing(false);
    }
  }, [processing, fetchStats]);

  const startCamera = useCallback(async () => {
    if (!scannerContainerRef.current) return;
    try {
      const { Html5QrcodeScanner } = await import('html5-qrcode');
      const scanner = new Html5QrcodeScanner('qr-reader', {
        fps: 10,
        qrbox: { width: 250, height: 250 },
      }, false);
      scanner.render(
        (decodedText: string) => handleQrScan(decodedText),
        () => { /* error callback — ignore decode failures */ },
      );
      scannerRef.current = scanner;
    } catch {
      message.error('Failed to start camera. Make sure html5-qrcode is installed.');
    }
  }, [handleQrScan]);

  const stopCamera = useCallback(() => {
    if (scannerRef.current) {
      (scannerRef.current as { clear: () => Promise<void> }).clear().catch(() => {});
      scannerRef.current = null;
    }
  }, []);

  useEffect(() => {
    if (mode === 'camera') {
      startCamera();
    } else {
      stopCamera();
    }
    return () => stopCamera();
  }, [mode, startCamera, stopCamera]);

  const handleManualCheckin = async (type: 'code' | 'email') => {
    if (!id) return;
    setProcessing(true);
    setScanResult(null);

    try {
      const body: Record<string, string> = { eventId: id };
      if (type === 'code') {
        body.ticketCode = manualCode.trim().toUpperCase();
      } else {
        body.holderEmail = manualEmail.trim();
      }

      const { data } = await api.post('/ticketed-events/checkin/manual', body);
      setScanResult({
        type: 'success',
        title: 'Checked In!',
        subtitle: `${data.ticket.ticketCode} — ${data.ticket.holderName || data.ticket.holderEmail}`,
        ticket: data.ticket,
      });
      setManualCode('');
      setManualEmail('');
      fetchStats();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Check-in failed';
      setScanResult({ type: 'error', title: msg, subtitle: '' });
    } finally {
      setProcessing(false);
    }
  };

  const resultColors: Record<string, string> = {
    success: '#52c41a',
    warning: '#faad14',
    error: '#ff4d4f',
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: '#0d1117',
      color: '#fff',
      padding: '16px',
    }}>
      <div style={{ maxWidth: 600, margin: '0 auto' }}>
        <Space style={{ marginBottom: 16 }}>
          <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(`/app/events/${id}`)}>Back</Button>
          <Title level={4} style={{ margin: 0, color: '#fff' }}>
            {(event as Record<string, unknown>)?.title as string || 'Check-in Scanner'}
          </Title>
        </Space>

        {/* Live stats */}
        {stats && (
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={8}>
              <Card size="small" style={{ background: '#161b22', border: '1px solid #30363d' }}>
                <Statistic title={<span style={{ color: '#8b949e' }}>Checked In</span>} value={stats.checkedIn} valueStyle={{ color: '#58a6ff' }} />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small" style={{ background: '#161b22', border: '1px solid #30363d' }}>
                <Statistic title={<span style={{ color: '#8b949e' }}>Remaining</span>} value={stats.remaining} valueStyle={{ color: '#f0883e' }} />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small" style={{ background: '#161b22', border: '1px solid #30363d' }}>
                <Statistic title={<span style={{ color: '#8b949e' }}>Total</span>} value={stats.totalTickets} valueStyle={{ color: '#8b949e' }} />
              </Card>
            </Col>
          </Row>
        )}

        {/* Scan result */}
        {scanResult && (
          <Card
            style={{
              marginBottom: 16,
              background: '#161b22',
              borderColor: resultColors[scanResult.type],
              borderWidth: 2,
            }}
          >
            <Result
              icon={
                scanResult.type === 'success' ? <CheckCircleOutlined style={{ color: '#52c41a' }} /> :
                scanResult.type === 'warning' ? <WarningOutlined style={{ color: '#faad14' }} /> :
                <CloseCircleOutlined style={{ color: '#ff4d4f' }} />
              }
              title={<span style={{ color: resultColors[scanResult.type] }}>{scanResult.title}</span>}
              subTitle={<span style={{ color: '#8b949e' }}>{scanResult.subtitle}</span>}
            />
          </Card>
        )}

        {/* Mode toggle */}
        <Space style={{ marginBottom: 16 }}>
          <Button
            type={mode === 'camera' ? 'primary' : 'default'}
            icon={<CameraOutlined />}
            onClick={() => setMode('camera')}
          >
            Camera
          </Button>
          <Button
            type={mode === 'manual' ? 'primary' : 'default'}
            icon={<KeyOutlined />}
            onClick={() => setMode('manual')}
          >
            Manual
          </Button>
        </Space>

        {mode === 'camera' && (
          <Card style={{ background: '#161b22', border: '1px solid #30363d', marginBottom: 16 }}>
            <div id="qr-reader" ref={scannerContainerRef} style={{ width: '100%' }} />
            {processing && <div style={{ textAlign: 'center', marginTop: 16 }}><Spin tip="Processing..." /></div>}
          </Card>
        )}

        {mode === 'manual' && (
          <Card style={{ background: '#161b22', border: '1px solid #30363d' }}>
            <Title level={5} style={{ color: '#c9d1d9' }}>Enter Ticket Code</Title>
            <Space.Compact style={{ width: '100%', marginBottom: 16 }}>
              <Input
                placeholder="ABCD-1234"
                value={manualCode}
                onChange={e => setManualCode(e.target.value)}
                onPressEnter={() => manualCode && handleManualCheckin('code')}
                style={{ textTransform: 'uppercase' }}
              />
              <Button
                type="primary"
                onClick={() => handleManualCheckin('code')}
                loading={processing}
                disabled={!manualCode.trim()}
              >
                Check In
              </Button>
            </Space.Compact>

            <Divider style={{ borderColor: '#30363d' }}>
              <Text style={{ color: '#8b949e' }}>or</Text>
            </Divider>

            <Title level={5} style={{ color: '#c9d1d9' }}>Look up by Email</Title>
            <Space.Compact style={{ width: '100%' }}>
              <Input
                placeholder="attendee@example.com"
                value={manualEmail}
                onChange={e => setManualEmail(e.target.value)}
                onPressEnter={() => manualEmail && handleManualCheckin('email')}
              />
              <Button
                type="primary"
                onClick={() => handleManualCheckin('email')}
                loading={processing}
                disabled={!manualEmail.trim()}
              >
                Check In
              </Button>
            </Space.Compact>
          </Card>
        )}
      </div>
    </div>
  );
}
