'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import { useStore } from '@/lib/store';
import {
  Bell,
  Mail,
  MessageSquare,
  Smartphone,
  CheckCheck,
  Filter,
  Settings,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { authFetch } from '@/lib/api';
import DataPagination from '@/components/shared/DataPagination';

interface NotificationItem {
  id: string;
  type: string;
  title: string;
  message: string;
  isRead: boolean;
  sentVia: string;
  createdAt: string;
  complaint?: { id: string; ticketNumber: string; status: string } | null;
}

const typeIcons: Record<string, React.ElementType> = {
  in_app: Bell,
  whatsapp: MessageSquare,
  email: Mail,
  sms: Smartphone,
};

const typeColors: Record<string, string> = {
  in_app: 'text-emerald-600 bg-emerald-100 dark:bg-emerald-950/30',
  whatsapp: 'text-green-600 bg-green-100 dark:bg-green-950/30',
  email: 'text-blue-600 bg-blue-100 dark:bg-blue-950/30',
  sms: 'text-purple-600 bg-purple-100 dark:bg-purple-950/30',
};

export default function NotificationPanel() {
  const { t } = useTranslation();
  const currentUser = useStore((s) => s.currentUser);
  const markNotificationRead = useStore((s) => s.markNotificationRead);
  const markAllNotificationsRead = useStore((s) => s.markAllNotificationsRead);
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState('all');
  const [page, setPage] = useState(1);
  const NOTIFICATIONS_PER_PAGE = 15;
  const [showSettings, setShowSettings] = useState(false);
  const [preferences, setPreferences] = useState({
    inApp: true,
    whatsapp: false,
    email: true,
    sms: false,
  });

  const fetchNotifications = useCallback(async () => {
    if (!currentUser?.id) return;
    setLoading(true);
    try {
      const res = await authFetch(`/api/notifications?userId=${currentUser.id}&limit=50`);
      if (res.ok) {
        const data = await res.json();
        setNotifications(data.notifications || []);
      }
    } catch (err) {
      console.error('Fetch notifications error:', err);
    } finally {
      setLoading(false);
    }
  }, [currentUser?.id]);

  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  const handleMarkRead = async (id: string) => {
    try {
      await authFetch('/api/notifications', {
        method: 'PUT',
        body: JSON.stringify({ notificationId: id }),
      });
      setNotifications((prev) =>
        prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
      );
      markNotificationRead(id);
    } catch (err) {
      console.error('Mark read error:', err);
    }
  };

  const handleMarkAllRead = async () => {
    if (!currentUser?.id) return;
    try {
      await authFetch('/api/notifications', {
        method: 'PUT',
        body: JSON.stringify({ markAllRead: true, userId: currentUser.id }),
      });
      setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
      markAllNotificationsRead();
    } catch (err) {
      console.error('Mark all read error:', err);
    }
  };

  const filtered = filterType === 'all'
    ? notifications
    : notifications.filter((n) => n.type === filterType);
  const totalPages = Math.ceil(filtered.length / NOTIFICATIONS_PER_PAGE);
  const paginatedNotifications = filtered.slice((page - 1) * NOTIFICATIONS_PER_PAGE, page * NOTIFICATIONS_PER_PAGE);

  const unreadCount = notifications.filter((n) => !n.isRead).length;

  return (
    <div className="space-y-4 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold">{t.nav.notifications}</h1>
          <p className="text-sm text-muted-foreground">{unreadCount} unread notifications</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleMarkAllRead}>
            <CheckCheck className="w-3.5 h-3.5 mr-1" /> Mark All Read
          </Button>
          <Button variant="outline" size="sm" onClick={() => setShowSettings(!showSettings)}>
            <Settings className="w-3.5 h-3.5 mr-1" /> Settings
          </Button>
        </div>
      </div>

      {/* Notification Settings */}
      {showSettings && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">Notification Preferences</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Bell className="w-4 h-4 text-emerald-600" />
                  <Label className="text-sm">In-App Notifications</Label>
                </div>
                <Switch checked={preferences.inApp} onCheckedChange={(v) => setPreferences((p) => ({ ...p, inApp: v }))} />
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <MessageSquare className="w-4 h-4 text-green-600" />
                  <Label className="text-sm">WhatsApp Notifications</Label>
                </div>
                <Switch checked={preferences.whatsapp} onCheckedChange={(v) => setPreferences((p) => ({ ...p, whatsapp: v }))} />
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Mail className="w-4 h-4 text-blue-600" />
                  <Label className="text-sm">Email Notifications</Label>
                </div>
                <Switch checked={preferences.email} onCheckedChange={(v) => setPreferences((p) => ({ ...p, email: v }))} />
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Smartphone className="w-4 h-4 text-purple-600" />
                  <Label className="text-sm">SMS Notifications</Label>
                </div>
                <Switch checked={preferences.sms} onCheckedChange={(v) => setPreferences((p) => ({ ...p, sms: v }))} />
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Filter */}
      <div className="flex items-center gap-3">
        <Select value={filterType} onValueChange={(v) => { setFilterType(v); setPage(1); }}>
          <SelectTrigger className="w-[150px] h-9">
            <SelectValue placeholder="Filter type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            <SelectItem value="in_app">In-App</SelectItem>
            <SelectItem value="whatsapp">WhatsApp</SelectItem>
            <SelectItem value="email">Email</SelectItem>
            <SelectItem value="sms">SMS</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Notification List */}
      {loading ? (
        <div className="p-8 text-center text-muted-foreground">{t.common.loading}</div>
      ) : filtered.length === 0 ? (
        <Card>
          <CardContent className="p-8 text-center">
            <Bell className="w-12 h-12 text-muted-foreground mx-auto mb-3" />
            <p className="text-sm text-muted-foreground">{t.common.noData}</p>
          </CardContent>
        </Card>
      ) : (
        <>
        <div className="space-y-2 max-h-[600px] overflow-y-auto">
          {paginatedNotifications.map((notification) => {
            const Icon = typeIcons[notification.type] || Bell;
            const colorClass = typeColors[notification.type] || 'text-gray-600 bg-gray-100';

            return (
              <Card
                key={notification.id}
                className={`transition-all duration-200 cursor-pointer hover:shadow-md ${
                  !notification.isRead ? 'border-l-4 border-l-emerald-500 bg-emerald-50/30 dark:bg-emerald-950/10' : ''
                }`}
                onClick={() => !notification.isRead && handleMarkRead(notification.id)}
              >
                <CardContent className="p-3">
                  <div className="flex items-start gap-3">
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${colorClass}`}>
                      <Icon className="w-4 h-4" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <p className={`text-sm ${!notification.isRead ? 'font-semibold' : 'font-medium'}`}>
                          {notification.title}
                        </p>
                        <div className="flex items-center gap-1.5 flex-shrink-0">
                          <Badge variant="outline" className="text-[9px] capitalize">{notification.type.replace('_', '-')}</Badge>
                          {!notification.isRead && (
                            <span className="w-2 h-2 rounded-full bg-emerald-500" />
                          )}
                        </div>
                      </div>
                      <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{notification.message}</p>
                      <p className="text-[10px] text-muted-foreground mt-1">
                        {new Date(notification.createdAt).toLocaleString()}
                        {notification.complaint && ` • ${notification.complaint.ticketNumber}`}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
        <DataPagination
          page={page}
          totalPages={totalPages}
          total={filtered.length}
          onPageChange={setPage}
          limit={NOTIFICATIONS_PER_PAGE}
        />
        </>
      )}
    </div>
  );
}
