"use client";

import { useEffect, useState } from "react";
import { Button } from "@app/components/ui/button";
import { Input } from "@app/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue
} from "@app/components/ui/select";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage
} from "@app/components/ui/form";
import {
    Credenza,
    CredenzaBody,
    CredenzaClose,
    CredenzaContent,
    CredenzaDescription,
    CredenzaFooter,
    CredenzaHeader,
    CredenzaTitle
} from "@app/components/Credenza";
import { toast } from "@app/hooks/useToast";
import { useTranslations } from "next-intl";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { Separator } from "@app/components/ui/separator";
import { ListRolesResponse } from "@server/routers/role";
import { ListUsersResponse } from "@server/routers/user";
import { ListSiteResourceRolesResponse } from "@server/routers/siteResource/listSiteResourceRoles";
import { ListSiteResourceUsersResponse } from "@server/routers/siteResource/listSiteResourceUsers";
import { Tag, TagInput } from "@app/components/tags/tag-input";
import { AxiosResponse } from "axios";
import { UserType } from "@server/types/UserTypes";

type InternalResourceData = {
    id: number;
    name: string;
    orgId: string;
    siteName: string;
    protocol: string;
    proxyPort: number | null;
    siteId: number;
    destinationIp?: string;
    destinationPort?: number;
};

type EditInternalResourceDialogProps = {
    open: boolean;
    setOpen: (val: boolean) => void;
    resource: InternalResourceData;
    orgId: string;
    onSuccess?: () => void;
};

export default function EditInternalResourceDialog({
    open,
    setOpen,
    resource,
    orgId,
    onSuccess
}: EditInternalResourceDialogProps) {
    const t = useTranslations();
    const api = createApiClient(useEnvContext());
    const [isSubmitting, setIsSubmitting] = useState(false);

    const formSchema = z.object({
        name: z.string().min(1, t("editInternalResourceDialogNameRequired")).max(255, t("editInternalResourceDialogNameMaxLength")),
        protocol: z.enum(["tcp", "udp"]),
        proxyPort: z.number().int().positive().min(1, t("editInternalResourceDialogProxyPortMin")).max(65535, t("editInternalResourceDialogProxyPortMax")),
        destinationIp: z.string(),
        destinationPort: z.number().int().positive().min(1, t("editInternalResourceDialogDestinationPortMin")).max(65535, t("editInternalResourceDialogDestinationPortMax")),
        roles: z.array(
            z.object({
                id: z.string(),
                text: z.string()
            })
        ).optional(),
        users: z.array(
            z.object({
                id: z.string(),
                text: z.string()
            })
        ).optional()
    });

    type FormData = z.infer<typeof formSchema>;

    const [allRoles, setAllRoles] = useState<{ id: string; text: string }[]>([]);
    const [allUsers, setAllUsers] = useState<{ id: string; text: string }[]>([]);
    const [activeRolesTagIndex, setActiveRolesTagIndex] = useState<number | null>(null);
    const [activeUsersTagIndex, setActiveUsersTagIndex] = useState<number | null>(null);
    const [loadingRolesUsers, setLoadingRolesUsers] = useState(false);

    const form = useForm<FormData>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            name: resource.name,
            protocol: resource.protocol as "tcp" | "udp",
            proxyPort: resource.proxyPort || undefined,
            destinationIp: resource.destinationIp || "",
            destinationPort: resource.destinationPort || undefined,
            roles: [],
            users: []
        }
    });

    const fetchRolesAndUsers = async () => {
        setLoadingRolesUsers(true);
        try {
            const [
                rolesResponse,
                resourceRolesResponse,
                usersResponse,
                resourceUsersResponse
            ] = await Promise.all([
                api.get<AxiosResponse<ListRolesResponse>>(`/org/${orgId}/roles`),
                api.get<AxiosResponse<ListSiteResourceRolesResponse>>(
                    `/site-resource/${resource.id}/roles`
                ),
                api.get<AxiosResponse<ListUsersResponse>>(`/org/${orgId}/users`),
                api.get<AxiosResponse<ListSiteResourceUsersResponse>>(
                    `/site-resource/${resource.id}/users`
                )
            ]);

            setAllRoles(
                rolesResponse.data.data.roles
                    .map((role) => ({
                        id: role.roleId.toString(),
                        text: role.name
                    }))
                    .filter((role) => role.text !== "Admin")
            );

            form.setValue(
                "roles",
                resourceRolesResponse.data.data.roles
                    .map((i) => ({
                        id: i.roleId.toString(),
                        text: i.name
                    }))
                    .filter((role) => role.text !== "Admin")
            );

            setAllUsers(
                usersResponse.data.data.users.map((user) => ({
                    id: user.id.toString(),
                    text: `${user.email || user.username}${user.type !== UserType.Internal ? ` (${user.idpName})` : ""}`
                }))
            );

            form.setValue(
                "users",
                resourceUsersResponse.data.data.users.map((i) => ({
                    id: i.userId.toString(),
                    text: `${i.email || i.username}${i.type !== UserType.Internal ? ` (${i.idpName})` : ""}`
                }))
            );
        } catch (error) {
            console.error("Error fetching roles and users:", error);
        } finally {
            setLoadingRolesUsers(false);
        }
    };

    useEffect(() => {
        if (open) {
            form.reset({
                name: resource.name,
                protocol: resource.protocol as "tcp" | "udp",
                proxyPort: resource.proxyPort || undefined,
                destinationIp: resource.destinationIp || "",
                destinationPort: resource.destinationPort || undefined,
                roles: [],
                users: []
            });
            fetchRolesAndUsers();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, resource]);

    const handleSubmit = async (data: FormData) => {
        setIsSubmitting(true);
        try {
            // Update the site resource
            await api.post(`/org/${orgId}/site/${resource.siteId}/resource/${resource.id}`, {
                name: data.name,
                protocol: data.protocol,
                proxyPort: data.proxyPort,
                destinationIp: data.destinationIp,
                destinationPort: data.destinationPort
            });

            // Update roles and users
            await Promise.all([
                api.post(`/site-resource/${resource.id}/roles`, {
                    roleIds: (data.roles || []).map((r) => parseInt(r.id))
                }),
                api.post(`/site-resource/${resource.id}/users`, {
                    userIds: (data.users || []).map((u) => u.id)
                })
            ]);

            toast({
                title: t("editInternalResourceDialogSuccess"),
                description: t("editInternalResourceDialogInternalResourceUpdatedSuccessfully"),
                variant: "default"
            });

            onSuccess?.();
            setOpen(false);
        } catch (error) {
            console.error("Error updating internal resource:", error);
            toast({
                title: t("editInternalResourceDialogError"),
                description: formatAxiosError(error, t("editInternalResourceDialogFailedToUpdateInternalResource")),
                variant: "destructive"
            });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Credenza open={open} onOpenChange={setOpen}>
            <CredenzaContent className="max-w-2xl">
                <CredenzaHeader>
                    <CredenzaTitle>{t("editInternalResourceDialogEditClientResource")}</CredenzaTitle>
                    <CredenzaDescription>
                        {t("editInternalResourceDialogUpdateResourceProperties", { resourceName: resource.name })}
                    </CredenzaDescription>
                </CredenzaHeader>
                <CredenzaBody>
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6" id="edit-internal-resource-form">
                            {/* Resource Properties Form */}
                            <div>
                                <h3 className="text-lg font-semibold mb-4">{t("editInternalResourceDialogResourceProperties")}</h3>
                                <div className="space-y-4">
                                    <FormField
                                        control={form.control}
                                        name="name"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>{t("editInternalResourceDialogName")}</FormLabel>
                                                <FormControl>
                                                    <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <div className="grid grid-cols-2 gap-4">
                                        <FormField
                                            control={form.control}
                                            name="protocol"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>{t("editInternalResourceDialogProtocol")}</FormLabel>
                                                    <Select
                                                        onValueChange={field.onChange}
                                                        value={field.value}
                                                    >
                                                        <FormControl>
                                                            <SelectTrigger>
                                                                <SelectValue />
                                                            </SelectTrigger>
                                                        </FormControl>
                                                        <SelectContent>
                                                            <SelectItem value="tcp">TCP</SelectItem>
                                                            <SelectItem value="udp">UDP</SelectItem>
                                                        </SelectContent>
                                                    </Select>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="proxyPort"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>{t("editInternalResourceDialogSitePort")}</FormLabel>
                                                    <FormControl>
                                                        <Input
                                                            type="number"
                                                            {...field}
                                                            onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                </div>
                            </div>

                            {/* Target Configuration Form */}
                            <div>
                                <h3 className="text-lg font-semibold mb-4">{t("editInternalResourceDialogTargetConfiguration")}</h3>
                                <div className="space-y-4">
                                    <div className="grid grid-cols-2 gap-4">
                                        <FormField
                                            control={form.control}
                                            name="destinationIp"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>{t("targetAddr")}</FormLabel>
                                                    <FormControl>
                                                        <Input {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="destinationPort"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>{t("targetPort")}</FormLabel>
                                                    <FormControl>
                                                        <Input
                                                            type="number"
                                                            {...field}
                                                            onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                </div>
                            </div>

                            {/* Access Control Section */}
                            <Separator />
                            <div>
                                <h3 className="text-lg font-semibold mb-4">
                                    {t("resourceUsersRoles")}
                                </h3>
                                {loadingRolesUsers ? (
                                    <div className="text-sm text-muted-foreground">
                                        {t("loading")}
                                    </div>
                                ) : (
                                    <div className="space-y-4">
                                        <FormField
                                            control={form.control}
                                            name="roles"
                                            render={({ field }) => (
                                                <FormItem className="flex flex-col items-start">
                                                    <FormLabel>{t("roles")}</FormLabel>
                                                    <FormControl>
                                                        <TagInput
                                                            {...field}
                                                            activeTagIndex={activeRolesTagIndex}
                                                            setActiveTagIndex={setActiveRolesTagIndex}
                                                            placeholder={t("accessRoleSelect2")}
                                                            size="sm"
                                                            tags={form.getValues().roles || []}
                                                            setTags={(newRoles) => {
                                                                form.setValue(
                                                                    "roles",
                                                                    newRoles as [Tag, ...Tag[]]
                                                                );
                                                            }}
                                                            enableAutocomplete={true}
                                                            autocompleteOptions={allRoles}
                                                            allowDuplicates={false}
                                                            restrictTagsToAutocompleteOptions={true}
                                                            sortTags={true}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                    <FormDescription>
                                                        {t("resourceRoleDescription")}
                                                    </FormDescription>
                                                </FormItem>
                                            )}
                                        />
                                        <FormField
                                            control={form.control}
                                            name="users"
                                            render={({ field }) => (
                                                <FormItem className="flex flex-col items-start">
                                                    <FormLabel>{t("users")}</FormLabel>
                                                    <FormControl>
                                                        <TagInput
                                                            {...field}
                                                            activeTagIndex={activeUsersTagIndex}
                                                            setActiveTagIndex={setActiveUsersTagIndex}
                                                            placeholder={t("accessUserSelect")}
                                                            tags={form.getValues().users || []}
                                                            size="sm"
                                                            setTags={(newUsers) => {
                                                                form.setValue(
                                                                    "users",
                                                                    newUsers as [Tag, ...Tag[]]
                                                                );
                                                            }}
                                                            enableAutocomplete={true}
                                                            autocompleteOptions={allUsers}
                                                            allowDuplicates={false}
                                                            restrictTagsToAutocompleteOptions={true}
                                                            sortTags={true}
                                                        />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                )}
                            </div>
                        </form>
                    </Form>
                </CredenzaBody>
                <CredenzaFooter>
                    <Button
                        variant="outline"
                        onClick={() => setOpen(false)}
                        disabled={isSubmitting}
                    >
                        {t("editInternalResourceDialogCancel")}
                    </Button>
                    <Button
                        type="submit"
                        form="edit-internal-resource-form"
                        disabled={isSubmitting}
                        loading={isSubmitting}
                    >
                         {t("editInternalResourceDialogSaveResource")}
                    </Button>
                </CredenzaFooter>
            </CredenzaContent>
        </Credenza>
    );
}
