"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { isApiSuccess } from "@/lib/api-messages";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { toastApiError } from "@/lib/toast-api-error";

import { LIST_HREF } from "./constants";
import type { UniqueIsinPriceChangeSettings } from "./schema";

const SAVE_HREF = "/dashboard/master-table/unique-isin-price-change/settings/save";

type Props = {
  initialSettings: UniqueIsinPriceChangeSettings;
};

export function UniqueIsinPriceChangeSettingsForm({ initialSettings }: Props) {
  const router = useRouter();
  const [notifyEnabled, setNotifyEnabled] = useState(initialSettings.notifyEnabled);
  const [thresholdPct, setThresholdPct] = useState(String(initialSettings.thresholdPct));
  const [webhookUrl, setWebhookUrl] = useState(initialSettings.rocketchatWebhookUrl);
  const [isSaving, setIsSaving] = useState(false);

  async function save(sendTest: boolean) {
    const parsedThreshold = Number(thresholdPct);
    if (!Number.isFinite(parsedThreshold) || parsedThreshold < 0) {
      toast.error("Alert threshold must be a number of 0 or more.");
      return;
    }

    setIsSaving(true);
    try {
      const result = await requestDashboardApi<{
        status?: string;
        message?: string;
        testResult?: { sent?: boolean; message?: string | null } | null;
      }>({
        url: SAVE_HREF,
        method: "POST",
        body: {
          notifyEnabled,
          thresholdPct: parsedThreshold,
          rocketchatWebhookUrl: webhookUrl.trim(),
          sendTest,
        },
        fallbackError: "Could not save ISIN price change settings.",
        validate: (data) => isApiSuccess(data),
      });

      const testMessage = result.testResult?.message;
      if (sendTest && result.testResult && !result.testResult.sent) {
        toast.warning(testMessage ?? result.message ?? "Settings saved.");
      } else {
        toast.success(result.message ?? "ISIN price change settings saved.");
      }
      router.refresh();
    } catch (error) {
      toastApiError(error, "Could not save ISIN price change settings.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <form
      className="space-y-6 max-w-xl"
      onSubmit={(event) => {
        event.preventDefault();
        void save(false);
      }}
    >
      <p className="text-muted-foreground text-sm">
        Send a Rocket.Chat alert when the absolute % price change between live and
        previous price exceeds the threshold. Each ISIN is alerted at most once per
        day for the same percentage.
      </p>

      <div className="flex items-center gap-2">
        <Checkbox
          id="notify_enabled"
          checked={notifyEnabled}
          onCheckedChange={(checked) => setNotifyEnabled(checked === true)}
        />
        <Label htmlFor="notify_enabled" className="font-normal">
          Enable notifications
        </Label>
      </div>

      <div className="space-y-2">
        <Label htmlFor="threshold_pct">Alert threshold (%)</Label>
        <Input
          id="threshold_pct"
          type="number"
          min={0}
          step="0.01"
          className="max-w-[200px]"
          value={thresholdPct}
          onChange={(event) => setThresholdPct(event.target.value)}
        />
        <p className="text-muted-foreground text-sm">
          Example: 5 means alert when change is +5% or −5% or more.
        </p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="rocketchat_webhook_url">Rocket.Chat webhook URL</Label>
        <Input
          id="rocketchat_webhook_url"
          type="url"
          placeholder="Leave empty to use the global webhook from Settings"
          value={webhookUrl}
          onChange={(event) => setWebhookUrl(event.target.value)}
        />
      </div>

      <div className="flex flex-wrap gap-2">
        <Button type="submit" disabled={isSaving}>
          Save settings
        </Button>
        <Button
          type="button"
          variant="outline"
          disabled={isSaving}
          onClick={() => void save(true)}
        >
          Save & send test alert
        </Button>
        <Button type="button" variant="ghost" asChild>
          <Link href={LIST_HREF}>Back to list</Link>
        </Button>
      </div>
    </form>
  );
}
