"use client"

import { useEffect, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Paperclip, Send } from "lucide-react"
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 { toast } from "@/components/ui/use-toast"
import { IMessage, ITicket } from "@/lib/interfaces/ticket/ticket.interface"
import Message from "@/components/ticket/message.component"
import TicketStatus from "@/components/ticket/ticket-status.component"
import { ITicketDetailApiResponseDto } from "@/lib/dto/ticket.dto"
import { getPersianDateTime } from "@/lib/helpers/date.helper"
import EmptyState from "@/components/common/empty-state.component"
import { useNumberQueryParam } from "@/hooks/useNumberQueryParam"
import { Form, FormField, FormItem, FormControl } from "@/components/ui/form"
import { useForm } from "react-hook-form"
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"
import { Separator } from "@/components/ui/separator"

type FormValues = {
    message: string
}

export default function TicketDetailView() {
    const id = useNumberQueryParam("id")

    // Hooks live in TicketDetail, so none runs after this return (rules of hooks).
    if (!id) {
        return null
    }

    return <TicketDetail key={id} id={id} />
}

function TicketDetail({ id }: { id: number }) {

    const methods = useForm<FormValues>({
        defaultValues: {
            message: ""
        }
    })

    const {
        handleSubmit,
        control,
        reset,
        watch
    } = methods

    const newMessage = watch("message")

    const [ticket, setTicket] = useState<ITicket | null>(null)
    const [messages, setMessages] = useState<IMessage[]>([])
    const [file, setFile] = useState<File | null>(null)
    const [isSending, setIsSending] = useState(false)
    const [loadError, setLoadError] = useState<string | null>(null)
    const chatRef = useRef<HTMLDivElement | null>(null)

    const [{ loading: fetchLoading }, refetchTicket] = useApi<ITicketDetailApiResponseDto>({
        url: ApiEndpoint("ticket", "detail", { id }),
        method: "GET",
    })

    const [{ loading: sendLoading }, sendMessage] = useApi<any>({
        url: ApiEndpoint("ticket", "message", { id }),
        method: "POST",
        timeout: MAX_UPLOAD_TIME_OUT
    })

    const loadTicketAndMessages = async () => {
        try {
            const response = await refetchTicket()
            const result = response?.body

            if (!result || !result.ok) {
                setLoadError(result?.msg || "خطا در دریافت اطلاعات تیکت")
                setTicket(null)
                setMessages([])
                return
            }

            setLoadError(null)
            setTicket(result.data.ticket)
            setMessages(result.data.messages)
        } catch (err: any) {
            setLoadError(getApiErrorMessage(err))
            setTicket(null)
            setMessages([])
        }
    }

    useEffect(() => {
        if (id) loadTicketAndMessages()
    }, [id])

    useEffect(() => {
        if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight
    }, [messages])

    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) {
            toast({
                title: "خطای فایل",
                description: ATTACHMENT_ERROR_MESSAGE,
                variant: "error",
            })
            e.target.value = ""
            return
        }

        setFile(file)
    }

    async function onSubmit(data: FormValues) {
        if (!data.message.trim()) {
            toast({ title: "خطا", description: "پیام خالی است", variant: "error" })
            return
        }

        if (isSending) return

        setIsSending(true)

        const formData = new FormData()
        formData.append("message", data.message.trim())

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

        try {
            const res = await sendMessage({ data: formData })
            const result = res?.body ?? res

            if (!result || !result.ok) {
                toast({ title: "خطا", description: result?.msg || "ارسال پیام ناموفق بود.", variant: "error" })
                setIsSending(false)
                return
            }

            toast({ title: "پیام ارسال شد", variant: "success" })

            const sentMessage: IMessage = {
                by_owner: true,
                message: data.message.trim(),
                created_at: getPersianDateTime(),
                attachments: file
                    ? [
                        {
                            file_name: file.name,
                            mime_type: file.type,
                            temporary_url: URL.createObjectURL(file),
                        },
                    ]
                    : [],
            }

            setMessages(prev => [...prev, sentMessage])

            reset({ message: "" })
            setFile(null)

            const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
            if (fileInput) fileInput.value = ""
        } catch (err: any) {
            toast({ title: "خطا", description: getApiErrorMessage(err), variant: "error" })
        } finally {
            setIsSending(false)
        }
    }

    return (
        <div className="flex flex-col flex-1 bg-background">
            <Loading loading={fetchLoading}>
                <ErrorBox
                    active={!!loadError}
                    title="خطا"
                    description={loadError}
                    showRetry={!!loadError}
                    onRetry={loadTicketAndMessages}
                >
                    <div className="flex items-center justify-between p-4 border-b">
                        <h2 className="text-base font-semibold">
                            {ticket?.title || "بدون عنوان"}
                        </h2>

                        <TicketStatus
                            isResolved={ticket?.is_resolved}
                            status={ticket?.status}
                        />
                    </div>

                    <div className="flex-1 overflow-y-auto px-4 mb-20" ref={chatRef}>
                        {messages.length === 0 ? (
                            <EmptyState
                                title="هیچ پیامی در این گفتگو وجود ندارد"
                                description="هنوز پیامی ثبت نشده است، اولین پیام را شما بفرستید."
                            />
                        ) : (
                            <div className="flex flex-col [&>*:not(:last-child)]:mb-3 px-2 py-2">
                                {messages.map((msg, index) => (
                                    <Message key={index} message={msg} />
                                ))}
                            </div>
                        )}
                    </div>

                    <Sticky>
                        <Separator className="mb-1" />
                        {ticket?.status === "close" ? (
                            <div className="text-center text-sm text-red-600">
                                این درخواست بسته شده است و امکان ادامه گفتگو وجود ندارد.
                            </div>
                        ) : (
                            <div>
                                <Form {...methods}>
                                    <form
                                        id="ticket-message-form"
                                        onSubmit={handleSubmit(onSubmit)}
                                    >
                                        <div className="w-full flex items-center px-4 py-3">

                                            <FormField
                                                control={control}
                                                name="message"
                                                rules={{ required: "پیام نمی‌تواند خالی باشد" }}
                                                render={({ field }) => (
                                                    <FormItem className="flex-1">
                                                        <FormControl>
                                                            <Input
                                                                placeholder="پیام خود را بنویسید..."
                                                                {...field}
                                                                disabled={isSending || sendLoading}
                                                            />
                                                        </FormControl>
                                                    </FormItem>
                                                )}
                                            />

                                            <input
                                                id="file-upload"
                                                type="file"
                                                className="hidden"
                                                onChange={handleFileChange}
                                            />

                                            <label htmlFor="file-upload">
                                                <Button
                                                    size="icon"
                                                    variant="outline"
                                                    className="mr-1 bg-white hover:bg-white active:bg-white"
                                                    asChild
                                                >
                                                    <span>
                                                        <Paperclip className="w-4 h-4" />
                                                    </span>
                                                </Button>
                                            </label>

                                            <Button
                                                className="mr-1"
                                                size="icon"
                                                type="submit"
                                                disabled={isSending || sendLoading}
                                            >
                                                <Send className="w-4 h-4" />
                                            </Button>

                                        </div>
                                    </form>
                                </Form>

                                {file && (
                                    <div className="border-t text-xs flex items-center justify-between text-muted-foreground px-4 py-2">
                                        <span>فایل پیوست: {file.name}</span>
                                        <button
                                            onClick={() => setFile(null)}
                                            className="text-red-500 hover:text-red-700"
                                        >
                                            حذف
                                        </button>
                                    </div>
                                )}

                            </div>
                        )}
                    </Sticky>

                </ErrorBox>
            </Loading>
        </div>
    )
}