import { FC, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CloseCircle } from 'iconsax-react'
import DefaulModal from '../../../components/DefaulModal'
import Select from '../../../components/Select'
import Input from '../../../components/Input'
import Button from '../../../components/Button'
import PageLoading from '../../../components/PageLoading'
import { toast } from '../../../components/Toast';
import { ErrorType } from '../../../helpers/types'
import { useGetWorkspaces } from '../../taskmanager/workspace/hooks/useWorkspaceData'
import { WorkspaceItemType } from '../../taskmanager/workspace/types/WorkspaceTypes'
import { useGetProjectsByWorkspace, useGetProject } from '../../taskmanager/project/hooks/useProjectData'
import { ProjectItem, ProjectTaskPhaseType } from '../../taskmanager/project/types/ProjectTypes'
import { useCreateTask, useUpdateTask } from '../../taskmanager/task/hooks/useTaskData'
import { useGetUsers } from '../../users/hooks/useUserData'
import { UserItemType } from '../../users/types/UserTypes'
import UserAvatar from '../../taskmanager/components/UserAvatar'
import type { SelectedUser } from '../../taskmanager/project/components/CreateProjectSidebar'

type Props = {
    ticketId: string
    ticketSubject: string
}

const CreateTaskFromTicket: FC<Props> = ({ ticketId, ticketSubject }) => {
    const { t } = useTranslation('global')
    const [open, setOpen] = useState(false)
    const [workspaceId, setWorkspaceId] = useState('')
    const [projectId, setProjectId] = useState('')
    const [taskPhaseId, setTaskPhaseId] = useState('')
    const [title, setTitle] = useState('')
    const [selectedUsers, setSelectedUsers] = useState<SelectedUser[]>([])
    const [userSelectValue, setUserSelectValue] = useState('')

    const getWorkspaces = useGetWorkspaces()
    const getProjects = useGetProjectsByWorkspace(workspaceId)
    const getProject = useGetProject(projectId)
    const getUsers = useGetUsers('')
    const createTask = useCreateTask()
    const updateTask = useUpdateTask()

    const workspaces: WorkspaceItemType[] =
        getWorkspaces.data?.data?.workspaces ??
        getWorkspaces.data?.data ??
        []

    const projects: ProjectItem[] =
        getProjects.data?.data?.projects ??
        getProjects.data?.data ??
        []

    const taskPhases: ProjectTaskPhaseType[] = useMemo(() => {
        const phases = getProject.data?.data?.taskPhases ?? []
        return [...phases].sort((a, b) => a.order - b.order)
    }, [getProject.data])

    const workspaceItems = workspaces.map((workspace) => ({
        label: workspace.name,
        value: workspace.id,
    }))

    const projectItems = projects.map((project) => ({
        label: project.name,
        value: project.id,
    }))

    const columnItems = taskPhases.map((phase) => ({
        label: phase.name,
        value: phase.id,
    }))

    const userItems =
        getUsers.data?.data?.users
            ?.filter((user: UserItemType) => !selectedUsers.some((selected) => selected.id === user.id))
            .map((user: UserItemType) => ({
                label: `${user.firstName} ${user.lastName}`,
                value: user.id,
            })) ?? []

    const selectedPhase = taskPhases.find((phase) => phase.id === taskPhaseId)

    const resetForm = () => {
        setWorkspaceId('')
        setProjectId('')
        setTaskPhaseId('')
        setTitle('')
        setSelectedUsers([])
        setUserSelectValue('')
    }

    const handleUserSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value
        if (!value) return

        const user = getUsers.data?.data?.users?.find((item: UserItemType) => item.id === value)

        if (user) {
            setSelectedUsers((prev) => [
                ...prev,
                {
                    id: user.id,
                    name: `${user.firstName} ${user.lastName}`,
                    profilePic: user.profilePic,
                },
            ])
        }

        setUserSelectValue('')
    }

    const handleRemoveUser = (id: string) => {
        setSelectedUsers((prev) => prev.filter((user) => user.id !== id))
    }

    const handleClose = () => {
        setOpen(false)
        resetForm()
    }

    useEffect(() => {
        if (open) {
            setTitle(ticketSubject)
        }
    }, [open, ticketSubject])

    const handleCreateTask = async () => {
        const trimmedTitle = title.trim()

        if (!workspaceId) {
            toast(t('ticket.select_workspace_required'), 'error')
            return
        }

        if (!projectId) {
            toast(t('ticket.select_project_required'), 'error')
            return
        }

        if (!taskPhaseId) {
            toast(t('ticket.select_column_required'), 'error')
            return
        }

        if (!trimmedTitle) {
            toast(t('errors.required'), 'error')
            return
        }

        const userIds = selectedUsers.map((user) => user.id)

        try {
            const response = await createTask.mutateAsync({
                title: trimmedTitle,
                taskPhaseId,
                order: selectedPhase?.tasks?.length ?? 0,
                projectId,
                ticketId,
                ...(userIds.length ? { userIds } : {}),
            })

            const taskId = response?.data?.task?.id ?? response?.data?.id

            if (taskId && userIds.length) {
                await updateTask.mutateAsync({ id: taskId, params: { userIds } })
            }

            toast(t('ticket.create_task_success'), 'success')
            handleClose()
        } catch (error) {
            toast((error as ErrorType).response?.data?.error?.message[0], 'error')
        }
    }

    const isLoadingOptions = getWorkspaces.isPending || getProjects.isPending || getProject.isPending
    const isSubmitting = createTask.isPending || updateTask.isPending

    return (
        <div className='bg-white p-6 rounded-3xl mt-8'>
            <div className='text-sm'>
                {t('ticket.create_task')}
            </div>

            <div className='flex justify-end mt-4'>
                <Button
                    label={t('ticket.create_task')}
                    onClick={() => setOpen(true)}
                    className='w-fit px-7'
                />
            </div>

            <DefaulModal
                open={open}
                close={handleClose}
                isHeader
                title_header={t('ticket.create_task_modal_title')}
            >
                {
                    isLoadingOptions && !workspaceItems.length ?
                        <div className='py-8'>
                            <PageLoading />
                        </div>
                        :
                        <div className='mt-4 flex flex-col gap-6'>
                            <Select
                                label={t('taskmanager.workspacename')}
                                placeholder={t('taskmanager.select_workspace')}
                                items={workspaceItems}
                                value={workspaceId}
                                onChange={(e) => {
                                    setWorkspaceId(e.target.value)
                                    setProjectId('')
                                    setTaskPhaseId('')
                                }}
                                className='border'
                            />

                            <Select
                                label={t('taskmanager.project_name')}
                                placeholder={t('ticket.select_project')}
                                items={projectItems}
                                value={projectId}
                                onChange={(e) => {
                                    setProjectId(e.target.value)
                                    setTaskPhaseId('')
                                }}
                                className='border'
                                disabled={!workspaceId || getProjects.isPending}
                            />

                            <Select
                                label={t('ticket.column')}
                                placeholder={t('ticket.select_column')}
                                items={columnItems}
                                value={taskPhaseId}
                                onChange={(e) => setTaskPhaseId(e.target.value)}
                                className='border'
                                disabled={!projectId || getProject.isPending}
                            />

                            <Input
                                label={t('taskmanager.task_title')}
                                value={title}
                                onChange={(e) => setTitle(e.target.value)}
                            />

                            <div>
                                <Select
                                    label={t('taskmanager.users')}
                                    placeholder={t('taskmanager.select_user')}
                                    items={userItems}
                                    value={userSelectValue}
                                    onChange={handleUserSelect}
                                    className='border'
                                />

                                <div className='mt-3 border border-dashed border-border rounded-xl p-4 flex gap-2 flex-wrap min-h-[52px]'>
                                    {selectedUsers.length === 0 ? (
                                        <div className='text-description w-full text-center text-xs'>
                                            {t('taskmanager.no_users_added')}
                                        </div>
                                    ) : (
                                        selectedUsers.map((user) => (
                                            <div key={user.id} className='bg-[#EBEEF5] flex gap-2 text-xs items-center px-2 py-2 rounded-lg'>
                                                <UserAvatar src={user.profilePic} alt={user.name} />
                                                <div>{user.name}</div>
                                                <CloseCircle
                                                    variant='Bold'
                                                    className='size-4 cursor-pointer'
                                                    color='red'
                                                    onClick={() => handleRemoveUser(user.id)}
                                                />
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>

                            <div className='flex justify-end'>
                                <Button
                                    label={t('ticket.create_task')}
                                    onClick={handleCreateTask}
                                    isLoading={isSubmitting}
                                    className='w-fit px-7'
                                />
                            </div>
                        </div>
                }
            </DefaulModal>
        </div>
    )
}

export default CreateTaskFromTicket
