'use client'

import { useState, useEffect } from 'react'
import { Alert, Button, Card } from 'flowbite-react'
import { FormProvider, useForm } from 'react-hook-form'
import { toast } from 'react-toastify'
import { yupResolver } from '@hookform/resolvers/yup'
import { useRouter } from 'next/navigation'

import { getAgent, updateAgent } from '@/lib/services/agent-services'
import buttonTheme from '@/lib/themes/button'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { handleApiError } from '@/lib/utils/error-handler'
import Form from '../../partials/Form'
import { AgentFormValues } from '../../types'
import { agentFormSchema } from '../../schema'
import { useAuth } from '@/lib/context/AuthContext'

interface MainContentProps {
  agentId: string
}

export default function MainContent({ agentId }: MainContentProps) {
  const router = useRouter()
  const [processing, setProcessing] = useState(false)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { user } = useAuth()

  const form = useForm({
    resolver: yupResolver(agentFormSchema),
  })

  // Load agent data
  useEffect(() => {
    const fetchAgent = async () => {
      try {
        setLoading(true)
        const agent = await getAgent(parseInt(agentId))

        // Set form values
        form.reset({
          business_name: agent.business_name || '',
          business_email: agent.business_email || '',
          business_address: agent.business_address || '',
          category: agent.category || '',
          guest_market: agent.guest_market || '',
          agreement_document_url: agent.agreement_document_url || '',
          bank_account: agent.bank_account
            ? {
                bank_id: agent.bank_account.bank_id,
                account_name: agent.bank_account.account_name || '',
                account_number: agent.bank_account.account_number || '',
              }
            : null,
          contact_person: {
            name: agent.contact_person?.name || '',
            email: agent.contact_person?.email || '',
            position: agent.contact_person?.position || '',
            phone_number: agent.contact_person?.phone_number || '',
          },
        })
      } catch (err) {
        handleApiError(err, 'An unexpected error occurred.')
      } finally {
        setLoading(false)
      }
    }

    if (agentId) {
      fetchAgent()
    }
  }, [agentId, form, router])

  const onSubmit = async (data: AgentFormValues) => {
    try {
      setProcessing(true)
      setError(null)

      await updateAgent(parseInt(agentId), {
        ...data,
      })

      form.reset()

      toast.success('Agent updated successfully')

      router.push('/agents')
    } catch (err) {
      handleApiError(err, 'An unexpected error occurred.', (formErrors) => {
        Object.keys(formErrors).forEach((field) => {
          form.setError(field as keyof AgentFormValues, {
            type: 'server',
            message: formErrors[field][0],
          })
        })
      })
    } finally {
      setProcessing(false)
    }
  }

  // Authorize User
  useEffect(() => {
    if (user && user.role !== 'super_admin' && user.role !== 'manager') {
      router.replace('/')
    }
  }, [user, router])

  if (loading) {
    return <FullPageLoader />
  }

  return (
    <Card className="mt-8 sm:mt-16 max-w-6xl shadow-none mx-auto">
      <section>
        <div>
          <h1 className="text-3xl font-semibold text-black mb-2">Edit Agent</h1>
          <p className="font-medium text-slate-500">
            Please update the agent information below.
          </p>
        </div>

        <FormProvider {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="mt-8">
            {error && (
              <Alert
                color="failure"
                className="mb-4"
                onDismiss={() => {
                  setError(null)
                }}
              >
                {error}
              </Alert>
            )}

            <Form />

            <div className="flex justify-end gap-4 mt-8">
              <Button
                type="button"
                color="alternative"
                theme={buttonTheme.button}
                as="a"
                href="/agents"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                color="default"
                theme={buttonTheme.button}
                disabled={processing}
              >
                {processing ? 'Updating...' : 'Update Agent'}
              </Button>
            </div>
          </form>
        </FormProvider>
      </section>
    </Card>
  )
}
