import { Alert, AlertDescription } from "@/components/ui/alert";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useFormState } from "react-dom";
import { useEffect } from "react";
import {
    createProxyHostAction,
    deleteProxyHostAction,
    updateProxyHostAction
} from "@/app/(dashboard)/proxy-hosts/actions";
import { INITIAL_ACTION_STATE } from "@/lib/actions";
import { AccessList } from "@/lib/models/access-lists";
import { Certificate } from "@/lib/models/certificates";
import { ProxyHost } from "@/lib/models/proxy-hosts";
import { AuthentikSettings } from "@/lib/settings";
import { AppDialog } from "@/components/ui/AppDialog";
import { AuthentikFields } from "./AuthentikFields";
import { DnsResolverFields } from "./DnsResolverFields";
import { LoadBalancerFields } from "./LoadBalancerFields";
import { SettingsToggles } from "./SettingsToggles";
import { UpstreamDnsResolutionFields } from "./UpstreamDnsResolutionFields";
import { UpstreamInput } from "./UpstreamInput";
import { GeoBlockFields } from "./GeoBlockFields";
import { WafFields } from "./WafFields";
import { MtlsFields } from "./MtlsConfig";
import { RedirectsFields } from "./RedirectsFields";
import { RewriteFields } from "./RewriteFields";
import type { CaCertificate } from "@/lib/models/ca-certificates";

export function CreateHostDialog({
    open,
    onClose,
    certificates,
    accessLists,
    authentikDefaults,
    initialData,
    caCertificates = []
}: {
    open: boolean;
    onClose: () => void;
    certificates: Certificate[];
    accessLists: AccessList[];
    authentikDefaults: AuthentikSettings | null;
    initialData?: ProxyHost | null;
    caCertificates?: CaCertificate[];
}) {
    const [state, formAction] = useFormState(createProxyHostAction, INITIAL_ACTION_STATE);

    useEffect(() => {
        if (state.status === "success") {
            setTimeout(onClose, 1000);
        }
    }, [state.status, onClose]);

    return (
        <AppDialog
            open={open}
            onClose={onClose}
            title={initialData ? "Duplicate Proxy Host" : "Create Proxy Host"}
            maxWidth="md"
            submitLabel="Create"
            onSubmit={() => {
                (document.getElementById("create-host-form") as HTMLFormElement)?.requestSubmit();
            }}
        >
            <form id="create-host-form" action={formAction} className="flex flex-col gap-5">
                {state.status !== "idle" && state.message && (
                    <Alert variant={state.status === "error" ? "destructive" : "default"}>
                        <AlertDescription>{state.message}</AlertDescription>
                    </Alert>
                )}
                <SettingsToggles
                    hstsSubdomains={initialData?.hsts_subdomains}
                    skipHttpsValidation={initialData?.skip_https_hostname_validation}
                    enabled={true}
                />
                <div>
                    <label className="text-sm font-medium mb-1 block">Name</label>
                    <Input
                        name="name"
                        placeholder="My Service"
                        defaultValue={initialData ? `${initialData.name} (Copy)` : ""}
                        required
                    />
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Domains</label>
                    <Textarea
                        name="domains"
                        placeholder="app.example.com"
                        defaultValue={initialData?.domains.join("\n") ?? ""}
                        required
                        rows={2}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                        One per line or comma-separated. Wildcards like *.example.com are supported.
                    </p>
                </div>
                <UpstreamInput defaultUpstreams={initialData?.upstreams} />
                <div>
                    <label className="text-sm font-medium mb-1 block">Certificate</label>
                    <Select name="certificate_id" defaultValue={String(initialData?.certificate_id ?? "")}>
                        <SelectTrigger>
                            <SelectValue placeholder="Managed by Caddy (Auto)" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="">Managed by Caddy (Auto)</SelectItem>
                            {certificates.map((cert) => (
                                <SelectItem key={cert.id} value={String(cert.id)}>
                                    {cert.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Access List</label>
                    <Select name="access_list_id" defaultValue={String(initialData?.access_list_id ?? "")}>
                        <SelectTrigger>
                            <SelectValue placeholder="None" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="">None</SelectItem>
                            {accessLists.map((list) => (
                                <SelectItem key={list.id} value={String(list.id)}>
                                    {list.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
                <RedirectsFields initialData={initialData?.redirects} />
                <RewriteFields initialData={initialData?.rewrite} />
                <div>
                    <label className="text-sm font-medium mb-1 block">Custom Pre-Handlers (JSON)</label>
                    <Textarea
                        name="custom_pre_handlers_json"
                        placeholder='[{"handler": "headers", ...}]'
                        defaultValue={initialData?.custom_pre_handlers_json ?? ""}
                        rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">Optional JSON array of Caddy handlers</p>
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Custom Reverse Proxy (JSON)</label>
                    <Textarea
                        name="custom_reverse_proxy_json"
                        placeholder='{"headers": {"request": {...}}}'
                        defaultValue={initialData?.custom_reverse_proxy_json ?? ""}
                        rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                        Deep-merge into reverse_proxy handler (only applies in proxy mode)
                    </p>
                </div>
                <AuthentikFields defaults={authentikDefaults} authentik={initialData?.authentik} />
                <LoadBalancerFields loadBalancer={initialData?.load_balancer} />
                <DnsResolverFields dnsResolver={initialData?.dns_resolver} />
                <UpstreamDnsResolutionFields upstreamDnsResolution={initialData?.upstream_dns_resolution} />
                <GeoBlockFields />
                <WafFields value={initialData?.waf} />
                <MtlsFields value={initialData?.mtls} caCertificates={caCertificates} />
            </form>
        </AppDialog>
    );
}

export function EditHostDialog({
    open,
    host,
    onClose,
    certificates,
    accessLists,
    caCertificates = []
}: {
    open: boolean;
    host: ProxyHost;
    onClose: () => void;
    certificates: Certificate[];
    accessLists: AccessList[];
    caCertificates?: CaCertificate[];
}) {
    const [state, formAction] = useFormState(updateProxyHostAction.bind(null, host.id), INITIAL_ACTION_STATE);

    useEffect(() => {
        if (state.status === "success") {
            setTimeout(onClose, 1000);
        }
    }, [state.status, onClose]);

    return (
        <AppDialog
            open={open}
            onClose={onClose}
            title="Edit Proxy Host"
            maxWidth="md"
            submitLabel="Save Changes"
            onSubmit={() => {
                (document.getElementById("edit-host-form") as HTMLFormElement)?.requestSubmit();
            }}
        >
            <form id="edit-host-form" action={formAction} className="flex flex-col gap-5">
                {state.status !== "idle" && state.message && (
                    <Alert variant={state.status === "error" ? "destructive" : "default"}>
                        <AlertDescription>{state.message}</AlertDescription>
                    </Alert>
                )}
                <SettingsToggles
                    hstsSubdomains={host.hsts_subdomains}
                    skipHttpsValidation={host.skip_https_hostname_validation}
                    enabled={host.enabled}
                />
                <div>
                    <label className="text-sm font-medium mb-1 block">Name</label>
                    <Input name="name" defaultValue={host.name} required />
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Domains</label>
                    <Textarea
                        name="domains"
                        defaultValue={host.domains.join("\n")}
                        rows={2}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                        One per line or comma-separated. Wildcards like *.example.com are supported.
                    </p>
                </div>
                <UpstreamInput defaultUpstreams={host.upstreams} />
                <div>
                    <label className="text-sm font-medium mb-1 block">Certificate</label>
                    <Select name="certificate_id" defaultValue={String(host.certificate_id ?? "")}>
                        <SelectTrigger>
                            <SelectValue placeholder="Managed by Caddy (Auto)" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="">Managed by Caddy (Auto)</SelectItem>
                            {certificates.map((cert) => (
                                <SelectItem key={cert.id} value={String(cert.id)}>
                                    {cert.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Access List</label>
                    <Select name="access_list_id" defaultValue={String(host.access_list_id ?? "")}>
                        <SelectTrigger>
                            <SelectValue placeholder="None" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="">None</SelectItem>
                            {accessLists.map((list) => (
                                <SelectItem key={list.id} value={String(list.id)}>
                                    {list.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
                <RedirectsFields initialData={host.redirects} />
                <RewriteFields initialData={host.rewrite} />
                <div>
                    <label className="text-sm font-medium mb-1 block">Custom Pre-Handlers (JSON)</label>
                    <Textarea
                        name="custom_pre_handlers_json"
                        defaultValue={host.custom_pre_handlers_json ?? ""}
                        rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">Optional JSON array of Caddy handlers</p>
                </div>
                <div>
                    <label className="text-sm font-medium mb-1 block">Custom Reverse Proxy (JSON)</label>
                    <Textarea
                        name="custom_reverse_proxy_json"
                        defaultValue={host.custom_reverse_proxy_json ?? ""}
                        rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                        Deep-merge into reverse_proxy handler (only applies in proxy mode)
                    </p>
                </div>
                <AuthentikFields authentik={host.authentik} />
                <LoadBalancerFields loadBalancer={host.load_balancer} />
                <DnsResolverFields dnsResolver={host.dns_resolver} />
                <UpstreamDnsResolutionFields upstreamDnsResolution={host.upstream_dns_resolution} />
                <GeoBlockFields
                    initialValues={{
                        geoblock: host.geoblock,
                        geoblock_mode: host.geoblock_mode,
                    }}
                />
                <WafFields value={host.waf} />
                <MtlsFields value={host.mtls} caCertificates={caCertificates} />
            </form>
        </AppDialog>
    );
}

export function DeleteHostDialog({
    open,
    host,
    onClose
}: {
    open: boolean;
    host: ProxyHost;
    onClose: () => void;
}) {
    const [state, formAction] = useFormState(deleteProxyHostAction.bind(null, host.id), INITIAL_ACTION_STATE);

    useEffect(() => {
        if (state.status === "success") {
            setTimeout(onClose, 1000);
        }
    }, [state.status, onClose]);

    return (
        <AppDialog
            open={open}
            onClose={onClose}
            title="Delete Proxy Host"
            maxWidth="sm"
            submitLabel="Delete"
            onSubmit={() => {
                (document.getElementById("delete-host-form") as HTMLFormElement)?.requestSubmit();
            }}
        >
            <form id="delete-host-form" action={formAction} className="flex flex-col gap-4">
                {state.status !== "idle" && state.message && (
                    <Alert variant={state.status === "error" ? "destructive" : "default"}>
                        <AlertDescription>{state.message}</AlertDescription>
                    </Alert>
                )}
                <p className="text-sm">
                    Are you sure you want to delete the proxy host <strong>{host.name}</strong>?
                </p>
                <p className="text-sm text-muted-foreground">
                    This will remove the configuration for:
                </p>
                <div className="pl-4">
                    <p className="text-sm text-muted-foreground">• Domains: {host.domains.join(", ")}</p>
                    <p className="text-sm text-muted-foreground">• Upstreams: {host.upstreams.join(", ")}</p>
                </div>
                <p className="text-sm text-destructive font-medium">
                    This action cannot be undone.
                </p>
            </form>
        </AppDialog>
    );
}
