/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
'use client';

import React, { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { X, Check, Camera } from 'lucide-react';

interface KYCData {
  email: string;
  bvn: string;
  nin: string;
  phoneNumber: string;
  address: string;
  selectedState: string;
  selectedCity: string;
}

export default function SelfiePage() {
  const router = useRouter();
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [facing, setFacing] = useState<'user' | 'environment'>('user');
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);
  const [kycData, setKycData] = useState<KYCData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Get KYC data from session storage
    const storedCompleteData = sessionStorage.getItem("completeKycData");
    if (storedCompleteData) {
      const data = JSON.parse(storedCompleteData);
      setKycData(data);
    } else {
      router.push('/kyc-profile');
      return;
    }

    initializeCamera();

    return () => {
      if (stream) {
        stream.getTracks().forEach(track => track.stop());
      }
    };
  }, [facing]);

  const initializeCamera = async () => {
    try {
      setIsLoading(true);
      
      if (stream) {
        stream.getTracks().forEach(track => track.stop());
      }

      const constraints = {
        video: {
          facingMode: facing,
          width: { ideal: 640 },
          height: { ideal: 480 }
        }
      };

      const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
      setStream(mediaStream);
      setHasPermission(true);
      
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
      }
    } catch (error) {
      console.error('Error accessing camera:', error);
      setHasPermission(false);
    } finally {
      setIsLoading(false);
    }
  };

  const requestPermission = async () => {
    await initializeCamera();
  };

  const takePicture = () => {
    if (!videoRef.current || !canvasRef.current) return;

    const canvas = canvasRef.current;
    const video = videoRef.current;
    
    // Set canvas dimensions to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    const ctx = canvas.getContext('2d');
    if (ctx) {
      // Draw the video frame to canvas
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      
      // Convert to blob
      canvas.toBlob((blob) => {
        if (blob && kycData) {
          // Create a file-like object
          const photoFile = new File([blob], 'selfie.jpg', {
            type: 'image/jpeg',
            lastModified: Date.now()
          });
          
          // Create object URL for preview (optional)
          const photoUrl = URL.createObjectURL(blob);
          
          // Store photo data and navigate to upload document
          const photoData = {
            file: photoFile,
            uri: photoUrl,
            // Add metadata for debugging
            metadata: {
              size: photoFile.size,
              type: photoFile.type,
              name: photoFile.name
            }
          };

          // Store in session storage - but we need to handle the File object specially
          // Since File objects can't be JSON.stringify'd directly, we'll store the URL
          // and recreate the File in the upload component
          sessionStorage.setItem('selfiePhoto', JSON.stringify({
            uri: photoUrl,
            metadata: photoData.metadata
          }));

          // We'll use a temporary storage approach
          (window as any).tempSelfieFile = photoFile;
          
          console.log('Selfie captured:', {
            fileSize: photoFile.size,
            fileType: photoFile.type,
            blobUrl: photoUrl
          });
          
          router.push('/document-upload');
        }
      }, 'image/jpeg', 0.9);
    }
  };

  // const toggleCameraFacing = () => {
  //   setFacing(current => current === 'user' ? 'environment' : 'user');
  // };

  const handleBack = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
    }
    router.back();
  };

  // Loading state
  if (isLoading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
          <p className="text-white">Initializing camera...</p>
        </div>
      </div>
    );
  }

  // Permission denied state
  if (hasPermission === false) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center px-6">
        <div className="text-center max-w-md">
          <Camera className="w-16 h-16 text-white mx-auto mb-6" />
          <p className="text-white text-center mb-6">
            We need your permission to show the camera
          </p>
          <button
            onClick={requestPermission}
            className="w-full bg-purple-600 hover:bg-purple-700 text-white font-medium py-3 px-6 rounded-lg transition-colors"
          >
            Grant Permission
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white flex flex-col">
      {/* Hidden canvas for photo capture */}
      <canvas
        ref={canvasRef}
        style={{ display: 'none' }}
      />
      {/* Camera container */}
      <div className="flex-1 flex items-center justify-center relative">
        <div className="relative">
        <div className="flex justify-center mb-6">
            {/* Progress indicator */}
          <div className="flex items-center justify-center mb-8">
            <div className="flex items-center">
              <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                ✓
              </div>
              <div className="w-16 h-0.5 bg-green-500"></div>
              <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                ✓
              </div>
              <div className="w-16 h-0.5 bg-green-500"></div>
              <div className="w-8 h-8 bg-green-500 rounded-full flex items-center justify-center text-white text-sm font-medium">
                ✓
              </div>
              <div className="w-16 h-0.5 bg-purple-600"></div>
              <div className="w-8 h-8 bg-purple-600 rounded-full flex items-center justify-center text-white text-sm font-medium">
                4
              </div>
            </div>
          </div>
          </div>
        <p className="text-black text-2xl mb-8 text-center">Take Selfie</p>
          {/* Oval-shaped camera view */}
          <div className="w-80 h-96 rounded-full overflow-hidden border-4 border-white/20">
            <video
              ref={videoRef}
              autoPlay
              playsInline
              muted
              className="w-full h-full object-cover"
              style={{ transform: facing === 'user' ? 'scaleX(-1)' : 'none' }}
            />
          </div>
        </div>
      </div>

      {/* Controls */}
      <div className="flex flex-col items-center pb-12">
        <div className="flex items-center justify-between w-80">
          {/* Cancel button */}
          <button
            onClick={handleBack}
            className="w-12 h-12 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center transition-colors"
          >
            <X className="w-6 h-6 text-white" />
          </button>

          {/* Flip camera button */}
          {/* <button
            onClick={toggleCameraFacing}
            className="px-6 py-3 bg-black/70 hover:bg-black/80 text-white rounded-full flex items-center space-x-2 transition-colors"
          >
            <RotateCw className="w-5 h-5" />
            <span>Flip Camera</span>
          </button> */}

          {/* Capture button */}
          <button
            onClick={takePicture}
            className="w-12 h-12 bg-green-500 hover:bg-green-600 rounded-full flex items-center justify-center transition-colors"
          >
            <Check className="w-6 h-6 text-white" />
          </button>
        </div>
      </div>
    </div>
  );
}