"use client"

import { useForm } from "react-hook-form"
import { useEffect, useState } from "react"
import { useVersionedRouter } from "@/hooks/use-versioned-router"

import { MessageCircle } from "lucide-react"
import Link from "@/components/common/versioned-link"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue
} from "@/components/ui/select"

import AttachmentInput from "@/components/common/attachment-input.component"
import { toast } from "@/components/ui/use-toast"

import { useTicketCategoryContext } from "@/lib/provider/ticket-category.provider"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { ApiEndpoint } from "@/lib/services/api.service"

import ErrorBox from "@/components/common/error-box.component"
import Loading from "@/components/common/loading.component"

import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from "@/components/ui/form"
import { Separator } from "@/components/ui/separator"
import { ALLOWED_ATTACHMENT_TYPES, ATTACHMENT_ERROR_MESSAGE, MAX_ATTACHMENT_SIZE, MAX_UPLOAD_TIME_OUT } from "@/constants/upload-file.constant"
import Sticky from "@/components/common/sticky.component"

type FormValues = {
    title: string
    description: string
    category: string
    attachment: File | null
}

export default function TicketCreateView() {
    const router = useVersionedRouter()

    const methods = useForm<FormValues>({
        defaultValues: {
            title: "",
            description: "",
            category: "",
            attachment: null
        }
    })

    const {
        handleSubmit,
        setValue,
        reset,
        watch,
        formState: { errors }
    } = methods

    const attachment = watch("attachment")
    const [fileName, setFileName] = useState<string | null>(null)

    const {
        categories,
        loadingCategories,
        categoryError,
        loadCategories
    } = useTicketCategoryContext()

    const [{ loading: createLoading }, createTicket] = useApi<any>({
        url: ApiEndpoint("ticket", "new"),
        method: "POST",
        timeout: MAX_UPLOAD_TIME_OUT
    })

    useEffect(() => {
        if (categories.length > 0) {
            setValue("category", String(categories[0].id))
        }
    }, [categories, setValue])

    useEffect(() => {
        if (categories.length === 0) {
            loadCategories()
        }
    }, [categories])

    function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0]
        if (!file) return

        const isSizeOk = file.size <= MAX_ATTACHMENT_SIZE
        const isTypeOk = ALLOWED_ATTACHMENT_TYPES.includes(file.type)

        if (!isSizeOk || !isTypeOk) {
            setValue("attachment", null, { shouldValidate: false })
            setFileName(null)

            toast({
                title: "خطای فایل",
                description: ATTACHMENT_ERROR_MESSAGE,
                variant: "error"
            })
            return
        }

        setValue("attachment", file, { shouldValidate: false })
        setFileName(file.name)
    }

    async function onSubmit(data: FormValues) {
        const formData = new FormData()
        formData.append("title", data.title.trim())
        formData.append("message", data.description.trim())
        formData.append("category_id", data.category)

        if (data.attachment) formData.append("attachment", data.attachment)

        try {
            const response = await createTicket({ data: formData })
            const result = response?.body

            if (!result?.ok) {
                toast({
                    title: "خطا",
                    description: result?.msg || "خطا در ایجاد درخواست",
                    variant: "error"
                })
                return
            }

            toast({
                title: "موفقیت آمیز!",
                description: result.msg || "درخواست شما ثبت شد",
                variant: "success"
            })

            reset({ title: "", description: "", category: "", attachment: null })
            setFileName(null)
            router.push("/ticket")
        } catch (err: any) {
            toast({
                title: "خطا",
                description: getApiErrorMessage(err),
                variant: "error"
            })
        }
    }

    return (
        <div className="flex flex-col flex-1 bg-background py-5 text-right mb-15">

            <Loading loading={loadingCategories}>
                <ErrorBox
                    active={!!categoryError}
                    title="خطا"
                    description={categoryError}
                    showRetry={!!categoryError}
                    onRetry={loadCategories}
                >

                    <div className="flex flex-col flex-1">

                        <div className="flex-1 overflow-y-auto min-h-0 px-4">
                            <Link href="/chats" className="flex items-start gap-2 rounded-2xl bg-ultra-soft text-ultra p-3 mb-4 text-caption leading-6">
                                <MessageCircle className="w-4 h-4 shrink-0 mt-1" aria-hidden="true" />
                                <span>
                                    پشتیبانی برای خرید، پرداخت، حساب و مشکلات برنامه است. سؤال درباره‌ی درس یا تمرین را
                                    <span className="font-bold"> از مربی دوره‌ات بپرس.</span>
                                </span>
                            </Link>
                            <div className="w-full max-w-md mx-auto flex flex-col [&>*:not(:last-child)]:mb-5">

                                <Form {...methods}>
                                    <form
                                        id="ticket-create-form"
                                        onSubmit={handleSubmit(onSubmit)}
                                        className="flex flex-col [&>*:not(:last-child)]:mb-5"
                                    >

                                        <FormField
                                            control={methods.control}
                                            name="title"
                                            rules={{ required: "عنوان نمی‌تواند خالی باشد" }}
                                            render={({ field }) => (
                                                <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                                    <FormLabel>عنوان</FormLabel>
                                                    <FormControl>
                                                        <Input placeholder="عنوان درخواست را وارد کنید" {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={methods.control}
                                            name="description"
                                            rules={{ required: "توضیحات نمی‌تواند خالی باشد" }}
                                            render={({ field }) => (
                                                <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                                    <FormLabel>توضیحات</FormLabel>
                                                    <FormControl>
                                                        <Textarea
                                                            rows={4}
                                                            placeholder="توضیحات درخواست خود را بنویسید"
                                                            {...field}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={methods.control}
                                            name="category"
                                            rules={{ required: "دسته بندی را انتخاب کنید" }}
                                            render={({ field }) => (
                                                <FormItem className="flex flex-col [&>*:not(:last-child)]:mb-2">
                                                    <FormLabel>دسته بندی</FormLabel>
                                                    <FormControl>
                                                        <Select
                                                            value={field.value}
                                                            onValueChange={(value) => field.onChange(value)}
                                                        >
                                                            <SelectTrigger className="w-full">
                                                                <SelectValue placeholder="انتخاب دسته بندی" />
                                                            </SelectTrigger>

                                                            <SelectContent>
                                                                {categories.map((cat) => (
                                                                    <SelectItem key={cat.id} value={String(cat.id)}>
                                                                        {cat.name}
                                                                    </SelectItem>
                                                                ))}
                                                            </SelectContent>
                                                        </Select>
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <div className="flex flex-col [&>*:not(:last-child)]:mb-3">
                                            <FormLabel>فایل پیوست (اختیاری)</FormLabel>

                                            <AttachmentInput
                                                fileName={fileName}
                                                hasFile={!!attachment}
                                                accept=".png,.jpg,.jpeg"
                                                onChange={handleFileChange}
                                            />

                                            <FormDescription>
                                                {ATTACHMENT_ERROR_MESSAGE}
                                            </FormDescription>
                                        </div>

                                    </form>
                                </Form>

                            </div>
                        </div>

                        <Sticky>
                            <Separator className="mb-3" />
                            <div className="w-full max-w-md mx-auto px-4">
                                <Button
                                    type="submit"
                                    form="ticket-create-form"
                                    size="lg"
                                    className="w-full rounded-xl mb-3"
                                    disabled={createLoading}
                                >
                                    ایجاد درخواست
                                </Button>
                            </div>
                        </Sticky>

                    </div>

                </ErrorBox>
            </Loading>

        </div>
    )

}
