/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react-hooks/exhaustive-deps */
// pages/kyc/upload-document.tsx or app/kyc/upload-document/page.tsx
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Button from '../../components/Button';
import { ArrowLeft, CloudUpload, FileText, CheckCircle } from 'lucide-react';
import ResponseModal from '../../components/ResponseModal';
import { toast } from 'sonner';

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

interface PhotoData {
  uri: string;
  file?: File;
}

interface SelectedFile {
  file: File;
  name: string;
  size: number;
  type: string;
}

export default function UploadDocumentPage() {
  const router = useRouter();
  const [kycData, setKycData] = useState<KYCData | null>(null);
  const [photoData, setPhotoData] = useState<PhotoData | null>(null);
  const [selectedFile, setSelectedFile] = useState<SelectedFile | null>(null);
  const [loading, setLoading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  
  // Modal state
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [modalMessage, setModalMessage] = useState('');
  const [isSuccess, setIsSuccess] = useState(false);

  useEffect(() => {
    // Get KYC data and photo from session storage
    const storedCompleteData = sessionStorage.getItem("completeKycData");
      const storedPhotoData = sessionStorage.getItem("selfiePhoto");

    if (storedCompleteData && storedPhotoData) {
        setKycData(JSON.parse(storedCompleteData));
        setPhotoData(JSON.parse(storedPhotoData));
        console.log('Retrieved KYC Data:', JSON.parse(storedCompleteData));
        console.log('Retrieved Photo Data:', JSON.parse(storedPhotoData));
    } else {
      router.push('/kyc-profile');
    }
  }, [router]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      handleFileSelection(files[0]);
    }
  }, []);

  const handleFileSelection = (file: File) => {
    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml', 'application/pdf'];
    if (!allowedTypes.includes(file.type)) {
      toast.error('Please upload a valid image file (JPG, PNG, GIF, SVG) or PDF.');
      return;
    }

    // Validate file size (max 5MB)
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      toast.error('File size should be less than 5MB.');
      return;
    }

    setSelectedFile({
      file,
      name: file.name,
      size: file.size,
      type: file.type
    });
  };

  const pickDocument = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*,application/pdf';
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        handleFileSelection(file);
      }
    };
    input.click();
  };

    const handleSubmit = async () => {

    if (!selectedFile || !kycData || !photoData) {
      toast.error('Please upload a document before submitting.');
      return;
    }

    setLoading(true);

    const formData = new FormData();
    formData.append('NIN', kycData.nin);
    formData.append('BVN', kycData.bvn);
    formData.append('MobileNumber', kycData.phoneNumber);
    formData.append('FullAddress', kycData.address);
    formData.append('City', kycData.selectedCity);
    formData.append('State', kycData.selectedState);
    formData.append('identityDocument', selectedFile.file);

    // Handle selfie photo
    if (photoData.file) {
      formData.append('profilePicture', photoData.file);
    } else {
      try {
        const response = await fetch(photoData.uri);
        const blob = await response.blob();
        const photoFile = new File([blob], 'selfie.jpg', { type: 'image/jpeg' });
        formData.append('profilePicture', photoFile);
      } catch (error) {
        console.error('Error processing selfie photo:', error);
        setModalTitle('Error!');
        setModalMessage('Error processing selfie photo. Please try again.');
        setIsSuccess(false);
        setModalVisible(true);
        setLoading(false);
        return;
      }
    }

    try {
      const token = localStorage.getItem('userToken') || sessionStorage.getItem('userToken');
      
      if (!token) {
        throw new Error('Authentication token not found');
      }
    
      const response = await fetch('https://webapidev.subacapital.co/api/kyc/create-kyc-profile', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      const data = await response.json();

      if (response.ok) {
        // Update user KYC status in local storage or state management
          localStorage.setItem('userKycStatus', data.data.kycVerify);
          console.log('KYC submission response:', data);
        
        setModalTitle('Success');
        setModalMessage(data.message);
        setIsSuccess(true);
        setModalVisible(true);

        // Clean up session storage
        sessionStorage.removeItem('completeKycData');
        sessionStorage.removeItem('selfiePhoto');
      } else {
        throw new Error(data.errors?.[0]?.message || 'Submission failed');
      }
    } catch (error: any) {
      console.error('Error submitting KYC:', error);
      setModalTitle('Error!');
      setModalMessage(error.message || 'An error occurred during submission. Please try again.');
      setIsSuccess(false);
      setModalVisible(true);
    } finally {
      setLoading(false);
    }
  };

  const handleDismissModal = () => {
    setModalVisible(false);
    if (isSuccess) {
      router.push('/dashboard'); // Navigate to dashboard on success
    } else {
      // Stay on current page to allow retry
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (!kycData || !photoData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex md:flex-row bg-white">

      <div className="w-full flex items-center justify-center p-6">
        <div className="w-full max-w-md">
          {/* Progress indicators */}
          <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>

          {/* Back button */}
          <button
            onClick={() => router.back()}
            className="flex items-center text-gray-600 hover:text-gray-800 mb-6 transition-colors"
            disabled={loading}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back
          </button>

          <h1 className="text-2xl font-semibold text-gray-900 mb-2">
            Upload your identity document
          </h1>
          <p className="text-gray-600 mb-8">
            Work ID, government-issued means of identification.
          </p>

          {/* Upload area */}
          <div
            className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors mb-6 ${
              dragActive 
                ? 'border-purple-500 bg-purple-50' 
                : 'border-gray-300 hover:border-purple-400 hover:bg-purple-50'
            }`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={pickDocument}
          >
            <div className="flex justify-center mb-4">
              <div className="w-10 h-10 bg-gray-100 rounded-xl flex items-center justify-center">
                <CloudUpload className="w-6 h-6 text-gray-600" />
              </div>
            </div>
            <p className="text-gray-900 font-medium mb-2">
              Click to upload an image or drag and drop
            </p>
            <p className="text-sm text-gray-500">
              SVG, PNG, JPG, GIF or PDF (max. 5MB)
            </p>
          </div>

          {/* Selected file display */}
          {selectedFile && (
            <div className="bg-white border border-gray-200 rounded-lg p-4 flex items-center space-x-3 mb-12">
              <div className="shrink-0">
                <FileText className="w-6 h-6 text-red-500" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-gray-900 truncate">
                  {selectedFile.name}
                </p>
                <p className="text-xs text-gray-500">
                  {formatFileSize(selectedFile.size)} • Uploaded
                </p>
              </div>
              <CheckCircle className="w-6 h-6 text-purple-600" />
            </div>
          )}

          {/* Action buttons */}
          <div className="flex gap-2 mt-16">
            <Button 
              onClick={handleSubmit}
              disabled={loading || !selectedFile}
              width="w-full"
                          type='submit'
            >
              {loading ? (
                <div className="flex items-center justify-center">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                   Submitting...
                </div>
              ) : (
                'Upload'
              )}
            </Button>

            <Button
                onClick={pickDocument}
                disabled={loading}
                borderColor='#1C1C1C26'
                border='1px'
                bgColor='#F5F5F533'
                textColor='text-purple-900'
                width="w-full"
                hover='purple-700'
            >
                Re-upload
            </Button>
          </div>
        </div>
      </div>

      {/* Response Modal */}
      <ResponseModal
        isOpen={modalVisible}
        title={modalTitle}
        message={modalMessage}
        isSuccess={isSuccess}
        onClose={handleDismissModal}
        buttonTitle={isSuccess ? 'OK' : 'Try Again'}
      />
    </div>
  );
}