"use client"

import type React from "react"

import { useState } from "react"
import { createIDUpload } from "./actions";
import AlertMessage from "@/components/alert-message";
import { documentType } from "@/prisma/generated/client";


export default function IDUpload({ userInfo }: { userInfo: any }) {

  const [alert, setAlert] = useState<{
    type: "success" | "error" | "info"
    message: string
    isVisible: boolean
  }>({
    type: "info",
    message: "",
    isVisible: false,
  })

  // document type
  const [documentType, setDocumentType] = useState<documentType>("ID")

  const [frontImagePreview, setFrontImagePreview] = useState<string | null>(null)
  const [backImagePreview, setBackImagePreview] = useState<string | null>(null)

  const handleFrontFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onloadend = () => {
        setFrontImagePreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const handleBackFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onloadend = () => {
        setBackImagePreview(reader.result as string)
      }

      reader.readAsDataURL(file)
    }
  }

  const onSubmit = async () => {
    try {
      const frontInput = document.getElementById('frontIDPicture') as HTMLInputElement;
      const backInput = document.getElementById('backIDPicture') as HTMLInputElement;

      const frontFile = frontInput?.files?.[0];
      const backFile = documentType == "ID" ? backInput?.files?.[0] : null;

      // Validate that both images are uploaded
      if (documentType == "ID") {
        if (!frontImagePreview || !backImagePreview) {
          setAlert({
            type: "error",
            message: "Please upload both front and back images of your ID",
            isVisible: true,
          })
          return
        }
      }
      else {
        if (!frontImagePreview) {
          setAlert({
            type: "error",
            message: "Please upload front image of your ID",
            isVisible: true,
          })
          return
        }
      }


      const uploadFile = async (file: File) => {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });

        const data = await response.json();
        if (!data.success) throw new Error('Upload failed');
        return data;
      };

      if (documentType == "ID") {
        let [frontUpload, backUpload] = await Promise.all([
          uploadFile(frontFile as File),
          uploadFile(backFile as File),
        ]);
        console.log('✅ Uploaded front:', frontUpload);
        console.log('✅ Uploaded back:', backUpload);
              // create in the database 
      try {
        const data = await createIDUpload({
          userId: userInfo.id,
          type: documentType,
          idImageUrlFront: frontUpload.fileName,
          idImageUrlBack: frontUpload.fileName
        })

        if (data.status == "fail") throw new Error("ID already uploaded");

        // Here you would typically send the images to your server
        // For demo purposes, we'll just show a success message
        setAlert({
          type: "success",
          message: "ID verification submitted successfully!",
          isVisible: true,
        })

      } catch (error) {
        setAlert({
          type: "error",
          message: "ID verification already submitted",
          isVisible: true,
        })
      }

      }
      
      else {
        let frontUpload = await uploadFile(frontFile as File);

        try {
        // create in the database 
        const data = await createIDUpload({
          userId: userInfo.id,
          type: documentType,
          idImageUrlFront: frontUpload.fileName,
        })

        if (data.status == "fail") throw new Error("ID already uploaded");

        // Here you would typically send the images to your server
        // For demo purposes, we'll just show a success message
        setAlert({
          type: "success",
          message: "ID verification submitted successfully!",
          isVisible: true,
        })

      } catch (error) {
        setAlert({
          type: "error",
          message: "ID verification already submitted",
          isVisible: true,
        })
      }
      }

    } catch (error) {
      console.error('❌ Error uploading files:', error);
    }
  };



  return (
    <>
      <AlertMessage
        type={alert.type}
        message={alert.message}
        isVisible={alert.isVisible}
        onClose={() => setAlert((prev) => ({ ...prev, isVisible: false }))}
      />
      <form
        onSubmit={async (e) => {
          e.preventDefault()
          // Handle form submission here
          await onSubmit()
        }}
        className="space-y-6 p-8 shadow rounded-lg max-w-4xl mx-auto bg-blue-50"
      >
        <p className="w-full text-center text-lg font-semibold mb-4">ID Verification</p>
        <div>
          <label htmlFor="idType" className="block text-lg font-medium text-gray-700">
            ID Type *
          </label>
          <select
            id="idType"
            name="idType"
            value={documentType}
            onChange={(e) => {
              setDocumentType(e.target.value as documentType)
            }}
            className="mt-1 py-3 px-2 font-medium block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
          >
            <option value="PASSPORT">Passport</option>
            <option value="DRIVING_LICENSE">Driving License</option>
            <option value="ID">National ID</option>
          </select>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* Front of ID */}
          <div className="!mt-8">
            <label htmlFor="frontIDPicture" className="block text-lg font-medium text-gray-700">
              Front of ID *
            </label>
            <div className="mt-4 flex flex-col items-center justify-center">
              <span className="inline-block h-40 w-64 rounded-md overflow-hidden bg-gray-100 mb-3">
                {frontImagePreview ? (
                  <img
                    src={frontImagePreview || "/placeholder.svg"}
                    alt="Front ID Preview"
                    className="h-full w-full object-cover text-gray-300"
                  />
                ) : (
                  <div className="h-full w-full flex items-center justify-center bg-gray-100">
                    <svg className="h-16 w-16 text-gray-300" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
                    </svg>
                  </div>
                )}
              </span>
              <input
                id="frontIDPicture"
                name="frontIDPicture"
                type="file"
                className="hidden"
                onChange={handleFrontFileChange}
              />
              <label
                htmlFor="frontIDPicture"
                className="cursor-pointer bg-blue-500 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded"
              >
                {frontImagePreview ? "Change" : "Upload Front"}
              </label>
            </div>
          </div>

          {/* Back of ID */}
          {documentType == "ID" && (
            <div className="!mt-8">
              <label htmlFor="backIDPicture" className="block text-lg font-medium text-gray-700">
                Back of ID *
              </label>
              <div className="mt-4 flex flex-col items-center justify-center">
                <span className="inline-block h-40 w-64 rounded-md overflow-hidden bg-gray-100 mb-3">
                  {backImagePreview ? (
                    <img
                      src={backImagePreview || "/placeholder.svg"}
                      alt="Back ID Preview"
                      className="h-full w-full object-cover text-gray-300"
                    />
                  ) : (
                    <div className="h-full w-full flex items-center justify-center bg-gray-100">
                      <svg className="h-16 w-16 text-gray-300" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
                      </svg>
                    </div>
                  )}
                </span>
                <input
                  id="backIDPicture"
                  name="backIDPicture"
                  type="file"
                  className="hidden"
                  onChange={handleBackFileChange}
                />
                <label
                  htmlFor="backIDPicture"
                  className="cursor-pointer bg-blue-500 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded"
                >
                  {backImagePreview ? "Change" : "Upload Back"}
                </label>
              </div>
            </div>
          )
          }
        </div>

        <div className="mt-6">
          <p className="text-sm text-gray-600">
            Please upload clear images of the front and back of your ID document. Make sure all information is clearly
            visible.
          </p>
        </div>
        <div className="mt-8 flex justify-center">
          <button
            type="submit"
            className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-8 rounded-md shadow-sm text-lg"
          >
            Submit
          </button>
        </div>
      </form>
    </>
  )
}

