"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"

interface Preferences {
  leadAssigned: boolean
  leadStatus: boolean
  noteAdded: boolean
  dailyDigest: boolean
  weeklyReport: boolean
}

const defaultPreferences: Preferences = {
  leadAssigned: true,
  leadStatus: true,
  noteAdded: false,
  dailyDigest: false,
  weeklyReport: true,
}

const notifications = [
  { id: "leadAssigned", title: "Lead Assigned", description: "When a lead is assigned to you" },
  { id: "leadStatus", title: "Status Changes", description: "When a lead's status is updated" },
  { id: "noteAdded", title: "Note Added", description: "When a note is added to your lead" },
  { id: "dailyDigest", title: "Daily Digest", description: "Receive a daily summary of lead activity" },
  { id: "weeklyReport", title: "Weekly Report", description: "Receive a weekly performance report" },
]

export function NotificationSettings() {
  const [prefs, setPrefs] = useState<Preferences>(defaultPreferences)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch("/api/notifications/preferences")
        if (res.ok) {
          const data = await res.json()
          setPrefs(data)
        }
      } catch {
        // ignore
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  async function handleSave() {
    setSaving(true)
    try {
      const res = await fetch("/api/notifications/preferences", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(prefs),
      })
      if (res.ok) {
        toast.success("Notification preferences saved")
      } else {
        toast.error("Failed to save preferences")
      }
    } catch {
      toast.error("Failed to save preferences")
    } finally {
      setSaving(false)
    }
  }

  function toggle(key: keyof Preferences) {
    setPrefs((prev) => ({ ...prev, [key]: !prev[key] }))
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Notification Settings</CardTitle>
        <CardDescription>
          Configure which notifications you want to receive.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-0">
        {notifications.map((n, i) => (
          <div
            key={n.id}
            className={`flex items-center justify-between py-4 ${i < notifications.length - 1 ? "border-b" : ""}`}
          >
            <div className="space-y-0.5">
              <Label htmlFor={n.id} className="text-sm font-medium">
                {n.title}
              </Label>
              <p className="text-sm text-muted-foreground">{n.description}</p>
            </div>
            <Switch
              id={n.id}
              disabled={loading}
              checked={prefs[n.id as keyof Preferences]}
              onCheckedChange={() => toggle(n.id as keyof Preferences)}
            />
          </div>
        ))}
        <div className="flex justify-end pt-4">
          <Button onClick={handleSave} disabled={loading || saving}>
            {saving ? "Saving..." : "Save Preferences"}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
