"use client"

import { useEffect, useState } from "react"
import { toast } from "sonner"
import { Bell, BellOff, Clock, Mail, Lock, Loader2 } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { cn } from "@/lib/utils"

interface NotificationType {
  type: string
  label: string
  enabled: boolean
  required: boolean
  canDisable: boolean
}

interface NotificationPreferences {
  emailEnabled: boolean
  quietHoursStart: string | null
  quietHoursEnd: string | null
  timezone: string
  digestFrequency: string
  types: NotificationType[]
  categoryPreferences: Record<string, boolean>
  isStaff: boolean
}

interface NotificationPreferencesFormProps {
  isPortal?: boolean
}

// Agrupamento de tipos de notificação
const TYPE_GROUPS = {
  lifecycle: {
    label: "Ciclo de vida do chamado",
    description: "Notificações sobre abertura, resolução e mudanças de status",
    types: ["ticket_created", "ticket_assigned", "ticket_resolved", "ticket_reopened", "ticket_status_changed", "ticket_priority_changed"],
  },
  communication: {
    label: "Comunicação",
    description: "Comentários e respostas nos chamados",
    types: ["comment_public", "comment_response", "comment_mention"],
  },
  sla: {
    label: "SLA e alertas",
    description: "Alertas de prazo e métricas",
    types: ["sla_at_risk", "sla_breached", "sla_daily_digest"],
  },
  security: {
    label: "Segurança",
    description: "Notificações de autenticação e acesso",
    types: ["security_password_reset", "security_email_verify", "security_email_change", "security_new_login", "security_invite"],
  },
}

export function NotificationPreferencesForm({ isPortal = false }: NotificationPreferencesFormProps) {
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [preferences, setPreferences] = useState<NotificationPreferences | null>(null)
  const [localTypePrefs, setLocalTypePrefs] = useState<Record<string, boolean>>({})

  useEffect(() => {
    loadPreferences()
  }, [])

  async function loadPreferences() {
    try {
      const response = await fetch("/api/notifications/preferences")
      if (!response.ok) {
        throw new Error("Erro ao carregar preferências")
      }
      const data = await response.json()
      setPreferences(data)

      // Inicializa preferências locais
      const typePrefs: Record<string, boolean> = {}
      data.types.forEach((t: NotificationType) => {
        typePrefs[t.type] = t.enabled
      })
      setLocalTypePrefs(typePrefs)
    } catch (error) {
      console.error("Erro ao carregar preferências:", error)
      toast.error("Não foi possível carregar suas preferências")
    } finally {
      setLoading(false)
    }
  }

  async function savePreferences() {
    if (!preferences) return

    setSaving(true)
    try {
      const response = await fetch("/api/notifications/preferences", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          emailEnabled: preferences.emailEnabled,
          quietHoursStart: preferences.quietHoursStart,
          quietHoursEnd: preferences.quietHoursEnd,
          timezone: preferences.timezone,
          digestFrequency: preferences.digestFrequency,
          typePreferences: localTypePrefs,
        }),
      })

      if (!response.ok) {
        throw new Error("Erro ao salvar preferências")
      }

      toast.success("Preferências salvas com sucesso")
    } catch (error) {
      console.error("Erro ao salvar preferências:", error)
      toast.error("Não foi possível salvar suas preferências")
    } finally {
      setSaving(false)
    }
  }

  function toggleType(type: string, enabled: boolean) {
    setLocalTypePrefs(prev => ({ ...prev, [type]: enabled }))
  }

  function toggleEmailEnabled(enabled: boolean) {
    setPreferences(prev => prev ? { ...prev, emailEnabled: enabled } : null)
  }

  function setQuietHours(start: string | null, end: string | null) {
    setPreferences(prev => prev ? { ...prev, quietHoursStart: start, quietHoursEnd: end } : null)
  }

  function setDigestFrequency(frequency: string) {
    setPreferences(prev => prev ? { ...prev, digestFrequency: frequency } : null)
  }

  if (loading) {
    return (
      <div className="space-y-6">
        {/* Skeleton do card de e-mail */}
        <Card>
          <CardHeader>
            <div className="flex items-center gap-2">
              <Skeleton className="h-5 w-5 rounded" />
              <Skeleton className="h-5 w-40" />
            </div>
            <Skeleton className="mt-1 h-4 w-64" />
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="space-y-1">
                <Skeleton className="h-4 w-28" />
                <Skeleton className="h-3 w-72" />
              </div>
              <Skeleton className="h-6 w-11 rounded-full" />
            </div>
          </CardContent>
        </Card>

        {/* Skeleton do card de tipos de notificacao */}
        <Card>
          <CardHeader>
            <div className="flex items-center gap-2">
              <Skeleton className="h-5 w-5 rounded" />
              <Skeleton className="h-5 w-44" />
            </div>
            <Skeleton className="mt-1 h-4 w-80" />
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Grupo 1 */}
            <div className="space-y-3">
              <div>
                <Skeleton className="h-4 w-40" />
                <Skeleton className="mt-1 h-3 w-64" />
              </div>
              <div className="space-y-2">
                {Array.from({ length: 3 }).map((_, i) => (
                  <div key={i} className="flex items-center justify-between rounded-lg border border-slate-200 p-4">
                    <div className="flex items-center gap-3">
                      <Skeleton className="h-8 w-8 rounded-full" />
                      <Skeleton className="h-4 w-36" />
                    </div>
                    <Skeleton className="h-6 w-11 rounded-full" />
                  </div>
                ))}
              </div>
            </div>

            {/* Grupo 2 */}
            <div className="space-y-3">
              <div>
                <Skeleton className="h-4 w-32" />
                <Skeleton className="mt-1 h-3 w-56" />
              </div>
              <div className="space-y-2">
                {Array.from({ length: 2 }).map((_, i) => (
                  <div key={i} className="flex items-center justify-between rounded-lg border border-slate-200 p-4">
                    <div className="flex items-center gap-3">
                      <Skeleton className="h-8 w-8 rounded-full" />
                      <Skeleton className="h-4 w-32" />
                    </div>
                    <Skeleton className="h-6 w-11 rounded-full" />
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Skeleton do botao salvar */}
        <div className="flex justify-end">
          <Skeleton className="h-10 w-40 rounded-md" />
        </div>
      </div>
    )
  }

  if (!preferences) {
    return (
      <Card>
        <CardContent className="py-8">
          <p className="text-center text-muted-foreground">
            Não foi possível carregar suas preferências de notificação.
          </p>
          <div className="flex justify-center mt-4">
            <Button onClick={loadPreferences}>Tentar novamente</Button>
          </div>
        </CardContent>
      </Card>
    )
  }

  // Filtra tipos visíveis para o usuário
  const visibleTypes = preferences.types

  // Agrupa tipos por categoria
  const groupedTypes: Record<string, NotificationType[]> = {}
  for (const [groupKey, group] of Object.entries(TYPE_GROUPS)) {
    const types = visibleTypes.filter(t => group.types.includes(t.type))
    if (types.length > 0) {
      groupedTypes[groupKey] = types
    }
  }

  return (
    <div className="space-y-6">
      {/* Configuração global de e-mail */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Notificações por e-mail
          </CardTitle>
          <CardDescription>
            Controle se deseja receber notificações por e-mail.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="space-y-0.5">
              <Label className="text-base">Receber e-mails</Label>
              <p className="text-sm text-muted-foreground">
                {preferences.emailEnabled
                  ? "Você receberá notificações por e-mail conforme suas preferências"
                  : "Todas as notificações por e-mail estão desativadas"}
              </p>
            </div>
            <Switch
              checked={preferences.emailEnabled}
              onCheckedChange={toggleEmailEnabled}
            />
          </div>

          {preferences.emailEnabled && preferences.isStaff && (
            <>
              <Separator />

              {/* Horário de silêncio - apenas staff */}
              <div className="space-y-4">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <Label className="text-base">Horário de silêncio</Label>
                </div>
                <p className="text-sm text-muted-foreground">
                  Durante este período, notificações não urgentes serão adiadas.
                </p>
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-2">
                    <Label htmlFor="quietStart" className="text-sm">Das</Label>
                    <Input
                      id="quietStart"
                      type="time"
                      value={preferences.quietHoursStart || ""}
                      onChange={(e) => setQuietHours(e.target.value || null, preferences.quietHoursEnd)}
                      className="w-32"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <Label htmlFor="quietEnd" className="text-sm">às</Label>
                    <Input
                      id="quietEnd"
                      type="time"
                      value={preferences.quietHoursEnd || ""}
                      onChange={(e) => setQuietHours(preferences.quietHoursStart, e.target.value || null)}
                      className="w-32"
                    />
                  </div>
                  {(preferences.quietHoursStart || preferences.quietHoursEnd) && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setQuietHours(null, null)}
                    >
                      Limpar
                    </Button>
                  )}
                </div>
              </div>

              <Separator />

              {/* Frequência de resumo - apenas staff */}
              <div className="space-y-4">
                <Label className="text-base">Frequência de resumo</Label>
                <p className="text-sm text-muted-foreground">
                  Como você prefere receber as notificações não urgentes.
                </p>
                <Select
                  value={preferences.digestFrequency}
                  onValueChange={setDigestFrequency}
                >
                  <SelectTrigger className="w-[200px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="immediate">Imediato</SelectItem>
                    <SelectItem value="daily">Resumo diário</SelectItem>
                    <SelectItem value="weekly">Resumo semanal</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* Tipos de notificação */}
      {preferences.emailEnabled && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Bell className="h-5 w-5" />
              Tipos de notificação
            </CardTitle>
            <CardDescription>
              Escolha quais tipos de notificação deseja receber.
              {!preferences.isStaff && (
                <span className="block mt-1 text-amber-600">
                  Algumas notificações são obrigatórias e não podem ser desativadas.
                </span>
              )}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-8">
            {Object.entries(groupedTypes).map(([groupKey, types]) => {
              const group = TYPE_GROUPS[groupKey as keyof typeof TYPE_GROUPS]
              return (
                <div key={groupKey} className="space-y-4">
                  <div>
                    <h3 className="font-medium">{group.label}</h3>
                    <p className="text-sm text-muted-foreground">{group.description}</p>
                  </div>
                  <div className="space-y-3">
                    {types.map((notifType) => {
                      const isEnabled = localTypePrefs[notifType.type] ?? notifType.enabled
                      return (
                        <div
                          key={notifType.type}
                          className={cn(
                            "flex items-center justify-between rounded-lg border p-4 transition-colors",
                            isEnabled ? "border-foreground/20 bg-foreground/[0.02]" : "border-border"
                          )}
                        >
                          <div className="flex items-center gap-3">
                            <div
                              className={cn(
                                "flex h-8 w-8 items-center justify-center rounded-full transition-colors",
                                notifType.required
                                  ? "bg-muted text-muted-foreground"
                                  : isEnabled
                                    ? "bg-foreground text-background"
                                    : "bg-muted text-muted-foreground"
                              )}
                            >
                              {notifType.required ? (
                                <Lock className="h-4 w-4" />
                              ) : isEnabled ? (
                                <Bell className="h-4 w-4" />
                              ) : (
                                <BellOff className="h-4 w-4" />
                              )}
                            </div>
                            <div>
                              <Label className={cn(
                                "text-sm font-medium transition-colors",
                                isEnabled ? "text-foreground" : "text-muted-foreground"
                              )}>
                                {notifType.label}
                              </Label>
                              {notifType.required && (
                                <Badge variant="secondary" className="ml-2 text-xs bg-foreground text-background">
                                  Obrigatório
                                </Badge>
                              )}
                            </div>
                          </div>
                          <Switch
                            checked={isEnabled}
                            onCheckedChange={(checked) => toggleType(notifType.type, checked)}
                            disabled={!notifType.canDisable}
                          />
                        </div>
                      )
                    })}
                  </div>
                </div>
              )
            })}
          </CardContent>
        </Card>
      )}

      {/* Botão de salvar */}
      <div className="flex justify-end">
        <Button onClick={savePreferences} disabled={saving}>
          {saving ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Salvando...
            </>
          ) : (
            "Salvar preferências"
          )}
        </Button>
      </div>
    </div>
  )
}
