import { useEffect, useRef, useState } from 'react';
import { BrowserMultiFormatReader, type IScannerControls } from '@zxing/browser';
import { invoke } from '@tauri-apps/api/core';
import { Camera, CheckCircle2, Loader2, QrCode, XCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { approveQrLogin } from '~/lib/mobile-api';
import { useMobileAuth } from '~/lib/auth';
import { getErrorMessage } from '~/lib/errors';

export function QrScanner() {
  const { token } = useMobileAuth();
  const videoRef = useRef<HTMLVideoElement>(null);
  const controlsRef = useRef<IScannerControls | null>(null);
  const [scanning, setScanning] = useState(false);
  const [status, setStatus] = useState<string | null>(null);
  const [approving, setApproving] = useState(false);

  useEffect(() => {
    return () => {
      controlsRef.current?.stop();
    };
  }, []);

  async function approvePayload(payload: string) {
    if (!token || approving) return;
    setApproving(true);
    setStatus('Проверяем QR-код...');
    try {
      const validated = await invoke<{ value: string }>('validate_qr_session_payload', { payload });
      await approveQrLogin(validated.value, token);
      setStatus('Вход на сайте подтверждён');
      controlsRef.current?.stop();
      setScanning(false);
    } catch (error) {
      setStatus(getErrorMessage(error, 'Не удалось подтвердить вход'));
    } finally {
      setApproving(false);
    }
  }

  async function startScan() {
    if (!videoRef.current) return;
    setStatus(null);
    setScanning(true);
    const reader = new BrowserMultiFormatReader();
    try {
      controlsRef.current = await reader.decodeFromVideoDevice(undefined, videoRef.current, (result, error) => {
        if (result?.getText()) {
          void approvePayload(result.getText());
        } else if (error) {
          setStatus('Камера активна, наведите её на QR-код');
        }
      });
    } catch (error) {
      setStatus(getErrorMessage(error, 'Не удалось открыть камеру'));
      setScanning(false);
    }
  }

  function stopScan() {
    controlsRef.current?.stop();
    setScanning(false);
  }

  return (
    <section className="rounded-[28px] bg-white p-4 shadow-sm">
      <div className="mb-4 flex items-center justify-between gap-3">
        <div>
          <h2 className="font-semibold">QR-вход</h2>
          <p className="text-sm text-[#667085]">Сканируйте QR-код на сайте, чтобы мгновенно подтвердить вход.</p>
        </div>
        <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-[#eef4ff] text-[#3390ec]">
          <QrCode className="h-5 w-5" />
        </div>
      </div>

      <div className="overflow-hidden rounded-[24px] bg-[#111827]">
        <video ref={videoRef} className="aspect-[4/3] w-full object-cover" muted playsInline />
      </div>

      {status ? (
        <div className="mt-3 flex items-center gap-2 rounded-2xl bg-[#f4f5f8] px-3 py-2 text-sm text-[#667085]">
          {status.includes('подтвержд') ? <CheckCircle2 className="h-4 w-4 text-emerald-600" /> : <XCircle className="h-4 w-4 text-[#667085]" />}
          {status}
        </div>
      ) : null}

      <div className="mt-4 flex gap-2">
        {scanning ? (
          <Button variant="secondary" className="flex-1" onClick={stopScan}>
            Остановить
          </Button>
        ) : (
          <Button className="flex-1" onClick={() => void startScan()}>
            <Camera className="h-4 w-4" />
            Сканировать QR
          </Button>
        )}
        {approving ? (
          <Button variant="secondary" size="icon" disabled>
            <Loader2 className="h-4 w-4 animate-spin" />
          </Button>
        ) : null}
      </div>
    </section>
  );
}
