"use client"

/*
 * File: SignUpScreen.tsx
 * Description: Main signup screen that manages the onboarding flow through multiple steps.
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import type React from "react"
import { useEffect, useState } from "react"
import { View, StyleSheet, StatusBar, Platform } from "react-native"
import { Colors } from "../../../../shared/src/theme"
import { useAppDispatch } from "../../../redux/hooks"
import { showError, showSuccess } from "../../../../shared/src/utils/helpers/Toast"

// Import all onboarding screens
import EmailScreen from "../components/EmailScreen"
import PasswordScreen from "../components/PasswordScreen"
import NameScreen from "../components/NameScreen"
import DocumentUploadScreen from "../components/DocumentUploadScreen"
import HospitalSelectionScreen from "../components/HospitalSelectionScreen"
import { authAPI } from "../services/authAPI"
import { setHospitals } from "../redux/hospitalSlice"

interface SignUpData {
  email: string
  password: string
  first_name: string
  last_name: string
  username:string
  id_photo_url: {}
  hospital_id: string
}

interface SignUpScreenProps {
    navigation: any
}

const SignUpScreen: React.FC<SignUpScreenProps> = ({ navigation }) => {
  const [currentStep, setCurrentStep] = useState(0)
  const [signUpData, setSignUpData] = useState<Partial<SignUpData>>({})
  const dispatch = useAppDispatch()

  const steps = ["email", "password", "name", "document", "hospital"]

  const handleEmailContinue = (email: string) => {
    setSignUpData((prev) => ({ ...prev, email }))
    setCurrentStep(1)
  }
  useEffect(()=>{
    fetchHospitals();
  },[])
  console.log('signup called')
  const fetchHospitals= async ()=>{

      try {

        const response:any = await  authAPI.gethospitals();
        console.log('hospital response',response)
        if(response.ok && response.data &&response.data.data) {
          //@ts-ignore
          dispatch(setHospitals(response.data.data))
        } else {
        showError('error while fetching hospital list')
        }
      } catch (error: any) {
       console.log('error',error)
      }
    
  }
  const onSignUpComplete=async (payload:SignUpData)=>{
    console.log('final payload',payload);
    try {
      const formData = new FormData();
      let role='radiologist'

      formData.append('email',payload.email);
      formData.append('password', payload.password);
      formData.append('first_name', payload.first_name);
      formData.append('last_name', payload.last_name);
      formData.append('username', payload.username);
      formData.append('dashboard_role',role);
      formData.append('hospital_id', payload.hospital_id);
      
      // Attach file (Node.js or React Native: use File or Blob API accordingly)
      const filePath = payload.id_photo_url.uri;
      const file = {
        uri: Platform.OS === 'android' ? filePath! : filePath!.replace('file://', ''), // for React Native
        name: 'id_photo',
        type: 'image/jpg',
      };
      formData.append('id_photo_url', file);
      console.log('payload prepared',formData);
      const response:any = await  authAPI.signup(formData);
      console.log('signup response',response)
      if(response.ok && response.data && response.data.success ) {
        //@ts-ignore
        showSuccess('Sign Up Successfully')
        navigation.navigate('Login');
        // dispatch(setHospitals(response.data.data))
      } else {
      showError('error while signup')
      }
    } catch (error: any) {
     console.log('error',error)
    }
  }
  const onBack=()=>{
   navigation.goBack()
  }
  const handlePasswordContinue = (password: string) => {
    setSignUpData((prev) => ({ ...prev, password }))
    setCurrentStep(2)
  }

  const handleNameContinue = (firstName: string, lastName: string,userName:string) => {
    setSignUpData((prev) => ({ ...prev, first_name : firstName, last_name : lastName ,username: userName}))
    setCurrentStep(3)
  }

  const handleDocumentContinue = (documentUri: string) => {
    setSignUpData((prev) => ({ ...prev, id_photo_url:documentUri }))
    setCurrentStep(4)
  }

  const handleHospitalContinue = (hospitalId: string) => {
    const finalData: SignUpData = {
      ...signUpData,
      hospital_id:hospitalId,
    } as SignUpData

    setSignUpData(finalData)

    // Show success message

    // Call completion handler
    if (onSignUpComplete) {
      onSignUpComplete(finalData)
    }

    // Here you would typically dispatch a signup action
    // dispatch(signUp(finalData))
  }

  const handleBack = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
    } else if (onBack) {
        onBack()
    }
  }

  const renderCurrentStep = () => {
    switch (currentStep) {
      case 0:
        return <EmailScreen onContinue={handleEmailContinue} onBack={handleBack} />
      case 1:
        return <PasswordScreen onContinue={handlePasswordContinue} onBack={handleBack} />
      case 2:
        return <NameScreen onContinue={handleNameContinue} onBack={handleBack} />
      case 3:
        return <DocumentUploadScreen onContinue={handleDocumentContinue} onBack={handleBack} />
      case 4:
        return <HospitalSelectionScreen onContinue={handleHospitalContinue} onBack={handleBack} />
      default:
        return <EmailScreen onContinue={handleEmailContinue} onBack={handleBack} />
    }
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor={Colors.background} />
      {renderCurrentStep()}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.background,
  },
})

export default SignUpScreen

/*
 * End of File: SignUpScreen.tsx
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */
