"use client";

import { useState } from "react";
import { Bell } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { SettingsCard } from "./settings-card";
import { SettingField } from "./setting-field";
import { SaveButton } from "./save-button";
import {
  updateNotificationSettings,
  type StoreSettingsData,
  type NotificationRuleInput,
} from "@/lib/actions/settings";

interface NotificationSettingsProps {
  settings: StoreSettingsData;
}

/**
 * Automated emails and alerts sent to customers and admins.
 */
export function NotificationSettings({ settings }: NotificationSettingsProps) {
  const [rules, setRules] = useState<NotificationRuleInput[]>(
    settings.notificationRules,
  );

  const toggle = (id: string, enabled: boolean) => {
    setRules((prev) => prev.map((r) => (r.id === id ? { ...r, enabled } : r)));
  };

  return (
    <SettingsCard
      title="Notifications"
      description="Choose which automatic notifications are sent."
      icon={<Bell className="h-4 w-4" />}
      footer={
        <SaveButton
          onSave={() =>
            updateNotificationSettings({
              rules,
              notificationFromEmail: settings.notificationFromEmail ?? undefined,
            })
          }
        />
      }
    >
      <div className="space-y-6">
        {rules.map((rule) => (
          <SettingField
            key={rule.id}
            id={`rule-${rule.id}`}
            label={rule.label}
            description={rule.description}
            controlClassName="sm:w-auto sm:shrink-0"
            control={
              <Switch
                id={`rule-${rule.id}`}
                checked={rule.enabled}
                onCheckedChange={(v) => toggle(rule.id, v)}
              />
            }
          />
        ))}

        <div className="rounded-lg border border-dashed px-4 py-3 text-sm text-muted-foreground">
          Notification emails are sent from{" "}
          <span className="font-medium text-foreground">
            notifications@sitechhub.com
          </span>
          . Delivery depends on the customer&apos;s contact preferences.
        </div>
      </div>
    </SettingsCard>
  );
}