'use client';

import { useState } from 'react';
import { Bell, Search, Loader2, Monitor, Smartphone, Tablet, Check, X } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';

interface DeviceDoc {
  id: string;
  productId: string;
  userId: string;
  deviceId: string;
  platform: string;
  pushToken?: string;
  appVersion?: string;
  osVersion?: string;
  lastSeenAt: string;
  createdAt: string;
}

interface NotificationPrefs {
  pushEnabled: boolean;
  emailEnabled: boolean;
  categories: Record<string, boolean>;
}

const platformIcons: Record<string, typeof Monitor> = {
  macos: Monitor,
  windows: Monitor,
  linux: Monitor,
  ios: Smartphone,
  android: Smartphone,
  ipad: Tablet,
};

export default function NotificationsPage() {
  const [userId, setUserId] = useState('');
  const [devices, setDevices] = useState<DeviceDoc[]>([]);
  const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);

  const handleSearch = async () => {
    if (!userId.trim()) return;
    setLoading(true);
    setSearched(true);
    try {
      const res = await fetch(`/api/notifications?userId=${encodeURIComponent(userId.trim())}`);
      if (res.ok) {
        const data = await res.json();
        setDevices(data.devices ?? []);
        setPrefs(data.prefs ?? null);
      } else {
        setDevices([]);
        setPrefs(null);
      }
    } catch {
      setDevices([]);
      setPrefs(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Notifications</h1>
        <p className="text-muted-foreground">
          View registered devices and notification preferences by user
        </p>
      </div>

      {/* Search */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Look Up User</CardTitle>
          <CardDescription>
            Search by user ID to view their devices and notification preferences
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="Enter user ID (e.g. usr_abc123...)"
              value={userId}
              onChange={e => setUserId(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              className="max-w-md"
            />
            <Button onClick={handleSearch} disabled={loading || !userId.trim()}>
              {loading ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Search className="mr-2 h-4 w-4" />
              )}
              Search
            </Button>
          </div>
        </CardContent>
      </Card>

      {searched && !loading && (
        <>
          {/* Notification Preferences */}
          {prefs && (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Notification Preferences</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-6 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Push:</span>
                    {prefs.pushEnabled ? (
                      <Badge
                        variant="secondary"
                        className="bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400"
                      >
                        <Check className="mr-1 h-3 w-3" /> Enabled
                      </Badge>
                    ) : (
                      <Badge
                        variant="secondary"
                        className="bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400"
                      >
                        <X className="mr-1 h-3 w-3" /> Disabled
                      </Badge>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Email:</span>
                    {prefs.emailEnabled ? (
                      <Badge
                        variant="secondary"
                        className="bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400"
                      >
                        <Check className="mr-1 h-3 w-3" /> Enabled
                      </Badge>
                    ) : (
                      <Badge
                        variant="secondary"
                        className="bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400"
                      >
                        <X className="mr-1 h-3 w-3" /> Disabled
                      </Badge>
                    )}
                  </div>
                </div>
                {Object.keys(prefs.categories).length > 0 && (
                  <div className="mt-3">
                    <p className="text-xs text-muted-foreground mb-2">Category Overrides:</p>
                    <div className="flex flex-wrap gap-2">
                      {Object.entries(prefs.categories).map(([cat, enabled]) => (
                        <Badge
                          key={cat}
                          variant="outline"
                          className={enabled ? 'border-emerald-300' : 'border-red-300 line-through'}
                        >
                          {cat}: {enabled ? 'on' : 'off'}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Devices */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Registered Devices ({devices.length})</CardTitle>
            </CardHeader>
            <CardContent>
              {devices.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Bell className="mx-auto h-10 w-10 mb-2 opacity-30" />
                  <p className="text-sm">No devices registered for this user</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {devices.map(device => {
                    const Icon = platformIcons[device.platform?.toLowerCase()] ?? Monitor;
                    return (
                      <div
                        key={device.id}
                        className="flex items-center justify-between rounded-lg border px-4 py-3"
                      >
                        <div className="flex items-center gap-3">
                          <Icon className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <div className="flex items-center gap-2">
                              <code className="text-xs font-mono">{device.deviceId}</code>
                              <Badge variant="outline" className="text-[10px]">
                                {device.platform}
                              </Badge>
                            </div>
                            <div className="flex items-center gap-3 mt-0.5 text-[11px] text-muted-foreground">
                              {device.appVersion && <span>v{device.appVersion}</span>}
                              {device.osVersion && <span>{device.osVersion}</span>}
                              <span>
                                Last seen {new Date(device.lastSeenAt).toLocaleDateString()}
                              </span>
                            </div>
                          </div>
                        </div>
                        {device.pushToken ? (
                          <Badge
                            variant="secondary"
                            className="bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400 text-[10px]"
                          >
                            Push token
                          </Badge>
                        ) : (
                          <Badge
                            variant="secondary"
                            className="bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400 text-[10px]"
                          >
                            No push token
                          </Badge>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
