'use client';
import React, { useState, useEffect } from 'react';
// import ReCAPTCHA from "react-google-recaptcha";
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Upload } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useGlobalContext } from '@/context/Provider';
import apis from '@/utils/apis';

interface DocumentRequirement {
  _id: string;
  type: string;
  response_type: 'image' | 'both_side_image' | 'number';
  document_name: string;
  is_required: boolean;
  is_expiry: boolean;
  createdAt: string;
  updatedAt: string;
}

interface DocumentUpload {
  requirement_id: string;
  document_name: string;
  response_type: string;
  is_required: boolean;
  is_expiry: boolean;
  document_value: string;
  document_value_back?: string;
  expiry_date?: string;
  frontFile?: File | null;
  backFile?: File | null;
}

const RequiredDocuments = () => {
  const router = useRouter();
  const { Toast } = useGlobalContext();
  const [loading, setLoading] = useState(false);

  const [showCaptcha, setShowCaptcha] = useState(false);
  const [captchaVerified, setCaptchaVerified] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState<string>("");

  const [documents, setDocuments] = useState<DocumentUpload[]>([]);
  const [documentRequirements, setDocumentRequirements] = useState<DocumentRequirement[]>([]);

  const handleCaptchaSuccess = (token: string | null) => {
    if (token) {
      setCaptchaVerified(true);
      setRecaptchaToken(token);
      Toast.success("Captcha verified successfully!");
      // Automatically proceed with submission after captcha verification
      proceedWithSubmit(token);
    }
  };

  const handleFileChange = async (requirementId: string, event: React.ChangeEvent<HTMLInputElement>, side: 'front' | 'back' = 'front') => {
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024;
      const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];

      if (!allowedTypes.includes(file.type)) {
        Toast.error('Only JPG and PNG images are allowed.');
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error('Image size cannot be more than 5MB.');
        return;
      }

      setDocuments(prev => prev.map(doc =>
        doc.requirement_id === requirementId
          ? { ...doc, [side === 'front' ? 'frontFile' : 'backFile']: file }
          : doc
      ));

      await handleUploadImage(requirementId, file, side);
    }
  };

  const handleUploadImage = async (requirementId: string, file: File, side: 'front' | 'back' = 'front') => {
    try {
      const apiRes = await apis.Common.uploadFile('file', file);

      setDocuments(prev => prev.map(doc =>
        doc.requirement_id === requirementId
          ? {
            ...doc,
            [side === 'front' ? 'document_value' : 'document_value_back']: apiRes?.key || ''
          }
          : doc
      ));

      Toast.success('Document uploaded successfully!');
    } catch (error) {
      Toast.error(error);
    }
  };

  useEffect(() => {
    fetchDocumentRequirements();
  }, []);

  const fetchDocumentRequirements = async () => {
    try {
      const apiRes = await apis.Documents.getDocuments('type=restaurant');
      if (apiRes?.data) {
        setDocumentRequirements(apiRes.data);

        const initialDocs = apiRes.data.map((req: DocumentRequirement) => ({
          requirement_id: req._id,
          document_name: req.document_name,
          response_type: req.response_type,
          is_required: req.is_required,
          is_expiry: req.is_expiry,
          document_value: '',
          document_value_back: req.response_type === 'both_side_image' ? '' : undefined,
          expiry_date: req.is_expiry ? '' : undefined,
          frontFile: null,
          backFile: req.response_type === 'both_side_image' ? null : undefined
        }));

        setDocuments(initialDocs);
      }
    } catch (error) {
      Toast.error('Failed to fetch document requirements.');
    }
  };

  const handleSubmit = async () => {
    // Validate required documents first
    const requiredDocs = documents.filter(doc => doc.is_required);
    const allRequiredUploaded = requiredDocs.every(doc => {
      if (doc.response_type === 'both_side_image') {
        return doc.document_value && doc.document_value_back;
      } else if (doc.response_type === 'image') {
        return doc.document_value;
      } else if (doc.response_type === 'number') {
        return doc.document_value;
      }
      return false;
    });

    if (!allRequiredUploaded) {
      Toast.error('Please upload all required documents.');
      return;
    }

    // Show captcha if not verified
    // if (!captchaVerified) {
    //   setShowCaptcha(true);
    //   return;
    // }

    // If already verified, proceed
    await proceedWithSubmit(recaptchaToken);
  };

  const proceedWithSubmit = async (token: string) => {
    try {
      setLoading(true);
      const payload = {
        documents: documents.map(doc => ({
          requirement_id: doc.requirement_id,
          driver_id: '',
          restaurant_id: sessionStorage.getItem('resId') || '',
          document_value: doc.document_value,
          document_value_back: doc.document_value_back,
          expiry_date: doc.expiry_date ? new Date(doc.expiry_date).toISOString() : undefined
        })),
        recaptcha_token: token
      };

      const apiRes = await apis.Documents.uploadDocument(payload);

      if (apiRes) {
        sessionStorage.setItem('documents', 'complete');
        router.push('/auth/restaurant/bankdetails');
      }

    } catch (error: any) {
      Toast.error(error.message || 'Failed to save documents.');
    } finally {
      setLoading(false);
    }
  };

  const handleNumberInput = (requirementId: string, value: string) => {
    setDocuments(prev => prev.map(doc =>
      doc.requirement_id === requirementId
        ? { ...doc, document_value: value }
        : doc
    ));
  };

  return (
    <div className="w-full space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {documents?.map((document) => (
          <div key={document.requirement_id} className="flex flex-col justify-between rounded-xl border border-dashed border-gray-300 bg-white p-5 hover:border-[var(--primary-brand)]/50 transition-colors">
            <div>
              <h3 className="mb-3 text-base font-semibold text-gray-900 capitalize">
                {document.document_name}
                {document.is_required && <span className="text-red-500 ml-1">*</span>}
              </h3>

              {document.response_type === 'number' ? (
                <Input
                  type="text"
                  placeholder={`Enter ${document.document_name} number`}
                  value={document.document_value}
                  onChange={(e) => handleNumberInput(document.requirement_id, e.target.value)}
                  className="w-full"
                />
              ) : (
                <div className="space-y-3">
                  {document.document_value ? (
                    <div className="relative overflow-hidden rounded-lg border border-gray-200 bg-gray-900">
                      <div className="aspect-video w-full">
                        <img
                          src={`${apis.BUCKET_ROOT || ''}${document.document_value}`}
                          className="h-full w-full object-cover"
                          alt={document.document_name}
                        />
                        <div className="absolute inset-0 flex items-center justify-center bg-black/40">
                          <label className="cursor-pointer rounded-md border border-white bg-black/30 px-3 py-1 text-xs font-medium text-white backdrop-blur-sm hover:bg-white hover:text-black transition-colors">
                            Change
                            <input
                              type="file"
                              className="hidden"
                              accept=".jpg,.jpeg,.png"
                              onChange={(e) => handleFileChange(document.requirement_id, e, 'front')}
                            />
                          </label>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="flex h-[110px] flex-col items-center justify-center gap-2 rounded-lg border border-gray-200 bg-gray-50/50 p-4 text-center">
                      <Upload className="h-6 w-6 text-gray-400" />
                      <label className="cursor-pointer">
                        <span className="inline-block rounded-full bg-[var(--primary-brand)] px-4 py-1.5 text-xs font-semibold text-white hover:opacity-90 transition-opacity shadow-sm">
                          + Upload Photo
                        </span>
                        <input
                          type="file"
                          className="hidden"
                          accept=".jpg,.jpeg,.png"
                          onChange={(e) => handleFileChange(document.requirement_id, e, 'front')}
                        />
                      </label>
                    </div>
                  )}

                  {document.response_type === 'both_side_image' && (
                    <div className="mt-3">
                      <h4 className="mb-2 text-xs font-medium text-gray-700">Back Side</h4>
                      {document.document_value_back ? (
                        <div className="relative overflow-hidden rounded-lg border border-gray-200 bg-gray-900">
                          <div className="aspect-video w-full">
                            <img
                              src={`${apis.BUCKET_ROOT || ''}${document.document_value_back}`}
                              className="h-full w-full object-cover"
                              alt={`${document.document_name} Back`}
                            />
                            <div className="absolute inset-0 flex items-center justify-center bg-black/40">
                              <label className="cursor-pointer rounded-md border border-white bg-black/30 px-3 py-1 text-xs font-medium text-white backdrop-blur-sm hover:bg-white hover:text-black transition-colors">
                                Change
                                <input
                                  type="file"
                                  className="hidden"
                                  accept=".jpg,.jpeg,.png"
                                  onChange={(e) => handleFileChange(document.requirement_id, e, 'back')}
                                />
                              </label>
                            </div>
                          </div>
                        </div>
                      ) : (
                        <div className="flex h-[110px] flex-col items-center justify-center gap-2 rounded-lg border border-gray-200 bg-gray-50/50 p-4 text-center">
                          <Upload className="h-6 w-6 text-gray-400" />
                          <label className="cursor-pointer">
                            <span className="inline-block rounded-full bg-[var(--primary-brand)] px-4 py-1.5 text-xs font-semibold text-white hover:opacity-90 transition-opacity shadow-sm">
                              + Upload Back Photo
                            </span>
                            <input
                              type="file"
                              className="hidden"
                              accept=".jpg,.jpeg,.png"
                              onChange={(e) => handleFileChange(document.requirement_id, e, 'back')}
                            />
                          </label>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* {showCaptcha && !captchaVerified && (
        <div className="mt-6 flex justify-center">
          <ReCAPTCHA
            sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_KEY || ""}
            onChange={handleCaptchaSuccess}
          />
        </div>
      )} */}

      <div className="space-y-3 pt-2">
        <Button
          onClick={handleSubmit}
          disabled={loading}
          className="h-11 w-full bg-[var(--primary-brand)] text-base font-semibold text-white hover:bg-[var(--primary-brand)]/90 disabled:bg-gray-300"
        >
          {loading ? 'Submitting...' : 'Submit'}
        </Button>

        <Button
          variant="outline"
          onClick={() => {
            sessionStorage.setItem('documents', 'complete');
            router.push('/auth/restaurant/bankdetails');
          }}
          className="h-11 w-full border-[var(--primary-brand)] text-base font-semibold text-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/10 hover:text-[var(--primary-brand)]"
        >
          Skip for now
        </Button>
      </div>
    </div>
  );
};

export default RequiredDocuments;