'use client'

import { useState } from 'react'
import {
  Bell,
  BellOff,
  Mail,
  Trash2,
  Plus,
  Save,
  Loader2,
  AlertCircle,
  Clock,
  Zap,
  Server as ServerIcon,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  useNotificationSettings,
  useUpdateNotificationSettings,
} from '@/hooks/use-enterprise-clients'
import { formatDistanceToNow } from 'date-fns'

interface NotificationSettingsPanelProps {
  clientId: string
}

export function NotificationSettingsPanel({ clientId }: NotificationSettingsPanelProps) {
  const { data: settings, isLoading, isError, refetch } = useNotificationSettings(clientId)
  const updateSettings = useUpdateNotificationSettings()

  const [newEmail, setNewEmail] = useState('')
  const [emailError, setEmailError] = useState<string | null>(null)
  const [localSettings, setLocalSettings] = useState<{
    enabled: boolean
    criticalErrorsOnly: boolean
    containerCrashes: boolean
    recipients: string[]
    cooldownMinutes: number
  } | null>(null)

  // Initialize local settings from fetched data
  if (settings && !localSettings) {
    setLocalSettings({
      enabled: settings.enabled,
      criticalErrorsOnly: settings.criticalErrorsOnly,
      containerCrashes: settings.containerCrashes,
      recipients: settings.recipients,
      cooldownMinutes: settings.cooldownMinutes,
    })
  }

  const hasChanges = localSettings && settings && (
    localSettings.enabled !== settings.enabled ||
    localSettings.criticalErrorsOnly !== settings.criticalErrorsOnly ||
    localSettings.containerCrashes !== settings.containerCrashes ||
    localSettings.cooldownMinutes !== settings.cooldownMinutes ||
    JSON.stringify(localSettings.recipients) !== JSON.stringify(settings.recipients)
  )

  const handleAddRecipient = () => {
    if (!localSettings) return

    const email = newEmail.trim().toLowerCase()
    if (!email) return

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(email)) {
      setEmailError('Invalid email format')
      return
    }

    // Check for duplicates
    if (localSettings.recipients.includes(email)) {
      setEmailError('Email already added')
      return
    }

    setLocalSettings({
      ...localSettings,
      recipients: [...localSettings.recipients, email],
    })
    setNewEmail('')
    setEmailError(null)
  }

  const handleRemoveRecipient = (email: string) => {
    if (!localSettings) return

    setLocalSettings({
      ...localSettings,
      recipients: localSettings.recipients.filter((r) => r !== email),
    })
  }

  const handleSave = async () => {
    if (!localSettings) return

    await updateSettings.mutateAsync({
      clientId,
      data: localSettings,
    })
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bell className="h-5 w-5" />
            Email Notifications
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Skeleton className="h-8 w-full" />
          <Skeleton className="h-24 w-full" />
          <Skeleton className="h-8 w-32" />
        </CardContent>
      </Card>
    )
  }

  if (isError || !settings) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Bell className="h-5 w-5" />
            Email Notifications
          </CardTitle>
        </CardHeader>
        <CardContent className="flex flex-col items-center gap-2 py-8">
          <AlertCircle className="h-8 w-8 text-destructive" />
          <p className="text-sm text-muted-foreground">Failed to load notification settings</p>
          <Button variant="outline" size="sm" onClick={() => refetch()}>
            Retry
          </Button>
        </CardContent>
      </Card>
    )
  }

  if (!localSettings) return null

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            {localSettings.enabled ? (
              <Bell className="h-5 w-5 text-primary" />
            ) : (
              <BellOff className="h-5 w-5 text-muted-foreground" />
            )}
            <CardTitle>Email Notifications</CardTitle>
          </div>
          <Switch
            checked={localSettings.enabled}
            onCheckedChange={(checked: boolean) =>
              setLocalSettings({ ...localSettings, enabled: checked })
            }
          />
        </div>
        <CardDescription>
          Receive email alerts when critical errors or container crashes are detected
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Notification Types */}
        <div className="space-y-4">
          <Label className="text-sm font-medium">Notify on</Label>
          <div className="space-y-3">
            <div className="flex items-center justify-between rounded-lg border p-3">
              <div className="flex items-center gap-3">
                <Zap className="h-4 w-4 text-red-600" />
                <div>
                  <p className="text-sm font-medium">Critical Errors Only</p>
                  <p className="text-xs text-muted-foreground">
                    Only notify for CRITICAL severity errors
                  </p>
                </div>
              </div>
              <Switch
                checked={localSettings.criticalErrorsOnly}
                onCheckedChange={(checked: boolean) =>
                  setLocalSettings({ ...localSettings, criticalErrorsOnly: checked })
                }
                disabled={!localSettings.enabled}
              />
            </div>
            <div className="flex items-center justify-between rounded-lg border p-3">
              <div className="flex items-center gap-3">
                <ServerIcon className="h-4 w-4 text-orange-600" />
                <div>
                  <p className="text-sm font-medium">Container Crashes</p>
                  <p className="text-xs text-muted-foreground">
                    Notify when containers crash or are OOM killed
                  </p>
                </div>
              </div>
              <Switch
                checked={localSettings.containerCrashes}
                onCheckedChange={(checked: boolean) =>
                  setLocalSettings({ ...localSettings, containerCrashes: checked })
                }
                disabled={!localSettings.enabled}
              />
            </div>
          </div>
        </div>

        {/* Recipients */}
        <div className="space-y-3">
          <Label className="text-sm font-medium">Recipients</Label>
          {localSettings.recipients.length > 0 ? (
            <div className="space-y-2">
              {localSettings.recipients.map((email) => (
                <div
                  key={email}
                  className="flex items-center justify-between rounded-lg border px-3 py-2"
                >
                  <div className="flex items-center gap-2">
                    <Mail className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm">{email}</span>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
                    onClick={() => handleRemoveRecipient(email)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">No recipients configured</p>
          )}
          <div className="flex gap-2">
            <div className="flex-1">
              <Input
                type="email"
                placeholder="Add email address..."
                value={newEmail}
                onChange={(e) => {
                  setNewEmail(e.target.value)
                  setEmailError(null)
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault()
                    handleAddRecipient()
                  }
                }}
                className={emailError ? 'border-destructive' : ''}
              />
              {emailError && (
                <p className="mt-1 text-xs text-destructive">{emailError}</p>
              )}
            </div>
            <Button variant="outline" size="icon" onClick={handleAddRecipient}>
              <Plus className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Cooldown */}
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <Clock className="h-4 w-4 text-muted-foreground" />
            <Label className="text-sm font-medium">Notification Cooldown</Label>
          </div>
          <div className="flex items-center gap-3">
            <Input
              type="number"
              min={5}
              max={1440}
              value={localSettings.cooldownMinutes}
              onChange={(e) =>
                setLocalSettings({
                  ...localSettings,
                  cooldownMinutes: parseInt(e.target.value) || 30,
                })
              }
              className="w-24"
              disabled={!localSettings.enabled}
            />
            <span className="text-sm text-muted-foreground">
              minutes between similar alerts
            </span>
          </div>
          <p className="text-xs text-muted-foreground">
            Prevents notification spam by waiting at least this long between alerts (5-1440 min)
          </p>
        </div>

        {/* Last Notification */}
        {settings.lastNotifiedAt && (
          <div className="rounded-lg bg-muted/50 px-3 py-2">
            <p className="text-xs text-muted-foreground">
              Last notification sent{' '}
              {formatDistanceToNow(new Date(settings.lastNotifiedAt), { addSuffix: true })}
            </p>
          </div>
        )}

        {/* Save Button */}
        <div className="flex items-center justify-between border-t pt-4">
          <div>
            {hasChanges && (
              <Badge variant="outline" className="text-xs">
                Unsaved changes
              </Badge>
            )}
          </div>
          <Button
            onClick={handleSave}
            disabled={!hasChanges || updateSettings.isPending}
          >
            {updateSettings.isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="mr-2 h-4 w-4" />
                Save Settings
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
