"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Users } from "lucide-react";
import { Controller, useForm } from "react-hook-form";

import { FormPageHeader, FormSaveBar, FormSelect } from "@/app/dashboard/_components/form";
import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { tenantFeatureWidgets } from "@/app/customer/_lib/dashboard-widget-registry-definitions";
import { cn } from "@/lib/utils";

import {
  AUM_CALC_MODE_OPTIONS,
  customerDashboardSettingsDefaults,
  customerDashboardSettingsSchema,
  type CustomerDashboardSettingsValues,
  type DashboardWidgetOption,
} from "./schema";

const LIST_HREF = "/dashboard/customers";

const FEATURE_WIDGETS = [
  ...tenantFeatureWidgets().map((widget) => ({
    key: widget.key,
    label: widget.label,
  })),
  { key: "top_change" as const, label: "Top 1 day change" },
];

const MODULE_TOGGLES = [
  { key: "deepdex_enabled", label: "Deepdex" },
  { key: "discussion_board_enabled", label: "Discussion Board" },
] as const;

type CustomerDashboardSettingsFormProps = {
  customerId: number;
  customerName?: string | null;
  initial?: CustomerDashboardSettingsValues;
  widgets: DashboardWidgetOption[];
  initialErrorMessage?: string | null;
};

function ToggleCard({
  id,
  label,
  checked,
  onCheckedChange,
}: {
  id: string;
  label: string;
  checked: boolean;
  onCheckedChange: (checked: boolean) => void;
}) {
  return (
    <label
      htmlFor={id}
      className="flex min-h-[88px] cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border bg-card px-3 py-4 text-center text-sm font-medium shadow-xs transition-colors hover:bg-muted/30"
    >
      <Checkbox
        id={id}
        checked={checked}
        onCheckedChange={(value) => onCheckedChange(value === true)}
      />
      <span>{label}</span>
    </label>
  );
}

export function CustomerDashboardSettingsForm({
  customerId,
  customerName = null,
  initial,
  widgets,
  initialErrorMessage = null,
}: CustomerDashboardSettingsFormProps) {
  const form = useForm<CustomerDashboardSettingsValues>({
    resolver: zodResolver(customerDashboardSettingsSchema),
    defaultValues: initial ?? customerDashboardSettingsDefaults,
  });

  const selectedWidgets = form.watch("dashboard_default_widgets");

  const { isSaving, submit } = useDashboardFormSubmit<CustomerDashboardSettingsValues>({
    mode: "update",
    id: customerId,
    createUrl: FRONTEND_ROUTES.customers.settingsSubmit,
    updateUrl: FRONTEND_ROUTES.customers.settingsSubmit,
    listHref: LIST_HREF,
    saveFailMessage: "Dashboard settings could not be saved.",
    messages: {
      createFail: "Dashboard settings could not be saved.",
      updateFail: "Dashboard settings could not be saved.",
      createSuccess: "Dashboard settings updated.",
      updateSuccess: "Dashboard settings updated.",
    },
  });

  const onSubmit = form.handleSubmit(async (values) => {
    await submit(values);
  });

  const toggleWidget = (widgetId: string, checked: boolean) => {
    const current = form.getValues("dashboard_default_widgets");
    form.setValue(
      "dashboard_default_widgets",
      checked ? [...new Set([...current, widgetId])] : current.filter((id) => id !== widgetId),
      { shouldDirty: true },
    );
  };

  return (
    <form onSubmit={onSubmit} className="flex flex-col">
      <ErrorBanner message={initialErrorMessage} className="mb-4" />

      <FormPageHeader
        backHref={LIST_HREF}
        parentLabel="Customers"
        currentLabel={customerName ? `${customerName} settings` : "Dashboard settings"}
        titleIcon={<Users className="size-4 text-primary" />}
        title="Corporate Dashboard Settings"
      />

      <div className="space-y-6">
        <section className="space-y-4">
          <h2 className="font-semibold text-base">Widgets</h2>

          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
            {FEATURE_WIDGETS.map(({ key, label }) => (
              <Controller
                key={key}
                name={key}
                control={form.control}
                render={({ field }) => (
                  <ToggleCard
                    id={key}
                    label={label}
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                )}
              />
            ))}
          </div>

          <div className="space-y-3">
            <Label className="text-sm font-medium">Default Dashboard Widgets</Label>
            <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {widgets.map((widget) => {
                const checked = selectedWidgets.includes(widget.id);
                return (
                  <label
                    key={widget.id}
                    htmlFor={`widget-${widget.id}`}
                    className={cn(
                      "flex cursor-pointer items-center gap-2 rounded-md border px-3 py-2 text-sm transition-colors hover:bg-muted/30",
                      checked && "border-primary/30 bg-primary/5",
                    )}
                  >
                    <Checkbox
                      id={`widget-${widget.id}`}
                      checked={checked}
                      onCheckedChange={(value) => toggleWidget(widget.id, value === true)}
                    />
                    <span>{widget.name}</span>
                  </label>
                );
              })}
            </div>
            <p className="text-muted-foreground text-xs">
              Enable feature flags to make widgets available in the customer portal settings page.
              Selected default widgets will be enabled by default for this account and its users.
              Users can still hide or show widgets from their own dashboard settings.
            </p>
          </div>
        </section>

        <Separator />

        <section className="space-y-4">
          <h2 className="font-semibold text-base">Modules</h2>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {MODULE_TOGGLES.map(({ key, label }) => (
              <Controller
                key={key}
                name={key}
                control={form.control}
                render={({ field }) => (
                  <ToggleCard
                    id={key}
                    label={label}
                    checked={field.value}
                    onCheckedChange={field.onChange}
                  />
                )}
              />
            ))}
          </div>
        </section>

        <Separator />

        <section className="space-y-4">
          <h2 className="font-semibold text-base">Reporting</h2>
          <div className="max-w-md">
            <Label htmlFor="aum_calc_mode" className="mb-2 block text-sm font-medium">
              AUM Calculation Mode
            </Label>
            <Controller
              name="aum_calc_mode"
              control={form.control}
              render={({ field }) => (
                <FormSelect
                  id="aum_calc_mode"
                  value={field.value}
                  onChange={field.onChange}
                  placeholder="Select mode"
                  options={AUM_CALC_MODE_OPTIONS}
                />
              )}
            />
          </div>
        </section>
      </div>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel="Save changes"
      />
    </form>
  );
}
