"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { AnimatedCard } from "@/components/ui/animated-card"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  Bell,
  MessageSquare,
  Star,
  Users,
  Building,
  AlertTriangle,
  CheckCircle,
  Info,
  Clock,
  Trash2,
  Check as MarkAsRead,
  Settings,
  Eye,
  EyeOff
} from "lucide-react"

// Mock notifications data
const mockNotifications = [
  {
    id: 1,
    type: "review",
    title: "New 5-star Review",
    message: "Sarah M. left a wonderful review: 'Excellent care for my mother. The staff is incredibly caring...'",
    timestamp: "2 hours ago",
    read: false,
    priority: "normal",
    actionUrl: "/facility-owner/reviews",
    icon: MessageSquare,
    iconColor: "text-blue-600"
  },
  {
    id: 2,
    type: "contact",
    title: "New Contact Inquiry",
    message: "The Johnson family submitted a contact form requesting more information about availability.",
    timestamp: "4 hours ago",
    read: false,
    priority: "high",
    actionUrl: "/facility-owner/dashboard",
    icon: Users,
    iconColor: "text-green-600"
  },
  {
    id: 3,
    type: "profile",
    title: "Profile Verification Complete",
    message: "Your facility profile has been successfully verified and is now visible to families.",
    timestamp: "1 day ago",
    read: true,
    priority: "normal",
    actionUrl: "/facility-owner/profile",
    icon: CheckCircle,
    iconColor: "text-green-600"
  },
  {
    id: 4,
    type: "system",
    title: "Monthly Analytics Available",
    message: "Your January performance report is ready. View insights about profile views, contacts, and reviews.",
    timestamp: "2 days ago",
    read: false,
    priority: "low",
    actionUrl: "/facility-owner/analytics",
    icon: Info,
    iconColor: "text-blue-600"
  },
  {
    id: 5,
    type: "review",
    title: "Review Needs Response",
    message: "Robert K. left a 4-star review that would benefit from your response to address parking concerns.",
    timestamp: "3 days ago",
    read: true,
    priority: "normal",
    actionUrl: "/facility-owner/reviews",
    icon: MessageSquare,
    iconColor: "text-orange-600"
  },
  {
    id: 6,
    type: "system",
    title: "Profile Update Recommended",
    message: "Consider adding more photos to your gallery. Facilities with 5+ photos get 40% more contact clicks.",
    timestamp: "5 days ago",
    read: true,
    priority: "low",
    actionUrl: "/facility-owner/profile",
    icon: Building,
    iconColor: "text-purple-600"
  },
  {
    id: 7,
    type: "alert",
    title: "Review Flagged for Content",
    message: "A review has been flagged and is under admin review. No action needed from you at this time.",
    timestamp: "1 week ago",
    read: true,
    priority: "high",
    actionUrl: "/facility-owner/reviews",
    icon: AlertTriangle,
    iconColor: "text-red-600"
  }
]

const mockSettings = {
  emailNotifications: {
    newReviews: true,
    contactInquiries: true,
    profileUpdates: false,
    systemUpdates: true,
    monthlyReports: true
  },
  pushNotifications: {
    newReviews: true,
    contactInquiries: true,
    profileUpdates: false,
    systemUpdates: false,
    monthlyReports: false
  }
}

export default function NotificationsPage() {
  const [notifications, setNotifications] = useState(mockNotifications)
  const [selectedTab, setSelectedTab] = useState("all")
  const [settings, setSettings] = useState(mockSettings)

  const filteredNotifications = notifications.filter(notification => {
    if (selectedTab === "all") return true
    if (selectedTab === "unread") return !notification.read
    if (selectedTab === "reviews") return notification.type === "review"
    if (selectedTab === "contacts") return notification.type === "contact"
    if (selectedTab === "system") return notification.type === "system" || notification.type === "alert"
    return true
  })

  const unreadCount = notifications.filter(n => !n.read).length
  const highPriorityCount = notifications.filter(n => n.priority === "high" && !n.read).length

  const markAsRead = (id: number) => {
    setNotifications(prev => prev.map(notification =>
      notification.id === id ? { ...notification, read: true } : notification
    ))
  }

  const markAllAsRead = () => {
    setNotifications(prev => prev.map(notification => ({ ...notification, read: true })))
  }

  const deleteNotification = (id: number) => {
    setNotifications(prev => prev.filter(notification => notification.id !== id))
  }

  const toggleSetting = (category: "emailNotifications" | "pushNotifications", setting: string) => {
    setSettings(prev => ({
      ...prev,
      [category]: {
        ...(prev[category as keyof typeof prev] || {}),
        [setting]: !(prev[category as keyof typeof prev] as any)?.[setting]
      }
    }))
  }

  const getPriorityBadge = (priority: string) => {
    switch (priority) {
      case "high":
        return <Badge variant="destructive" className="text-xs">High</Badge>
      case "low":
        return <Badge variant="secondary" className="text-xs">Low</Badge>
      default:
        return null
    }
  }

  const getTimeAgo = (timestamp: string) => {
    // In a real app, this would calculate actual time difference
    return timestamp
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-primary text-3xl md:text-4xl font-bold text-gray-900">
            Notifications
          </h1>
          <p className="font-body text-xl text-gray-600 mt-2">
            Stay updated with important facility alerts and messages
          </p>
        </div>
        <div className="flex items-center gap-3">
          {unreadCount > 0 && (
            <AnimatedButton 
              variant="outline" 
              onClick={markAllAsRead}
              className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white"
            >
              <MarkAsRead className="h-4 w-4 mr-2" />
              Mark All Read
            </AnimatedButton>
          )}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <AnimatedCard>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="font-body text-sm font-medium">Unread</CardTitle>
            <Bell className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="font-primary text-3xl font-bold">{unreadCount}</div>
            <p className="font-body text-xs text-muted-foreground">
              New notifications
            </p>
          </CardContent>
        </AnimatedCard>

        <AnimatedCard>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="font-body text-sm font-medium">High Priority</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="font-primary text-3xl font-bold text-red-600">{highPriorityCount}</div>
            <p className="font-body text-xs text-muted-foreground">
              Needs attention
            </p>
          </CardContent>
        </AnimatedCard>

        <AnimatedCard>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="font-body text-sm font-medium">Total</CardTitle>
            <MessageSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="font-primary text-3xl font-bold">{notifications.length}</div>
            <p className="font-body text-xs text-muted-foreground">
              All notifications
            </p>
          </CardContent>
        </AnimatedCard>
      </div>

      {/* Notifications Content */}
      <Tabs value={selectedTab} onValueChange={setSelectedTab}>
        <TabsList className="grid w-full grid-cols-5 h-12 font-primary">
          <TabsTrigger value="all">All</TabsTrigger>
          <TabsTrigger value="unread">Unread ({unreadCount})</TabsTrigger>
          <TabsTrigger value="reviews">Reviews</TabsTrigger>
          <TabsTrigger value="contacts">Contacts</TabsTrigger>
          <TabsTrigger value="system">System</TabsTrigger>
        </TabsList>

        <TabsContent value={selectedTab} className="space-y-4 mt-6">
          {filteredNotifications.length === 0 ? (
            <AnimatedCard>
              <CardContent className="text-center py-12">
                <Bell className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <h3 className="font-primary text-2xl font-semibold text-gray-900 mb-2">
                  No Notifications
                </h3>
                <p className="font-body text-lg text-gray-600">
                  {selectedTab === "unread" 
                    ? "You're all caught up! No unread notifications."
                    : "No notifications in this category."}
                </p>
              </CardContent>
            </AnimatedCard>
          ) : (
            filteredNotifications.map((notification) => (
              <AnimatedCard 
                key={notification.id} 
                className={`${!notification.read ? 'border-l-4 border-l-[#3F5CEA] bg-blue-50/30' : ''} hover:shadow-md transition-shadow`}
              >
                <CardContent className="p-6">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-4 flex-1">
                      <div className={`p-2 rounded-full bg-gray-100 ${notification.iconColor}`}>
                        <notification.icon className="h-5 w-5" />
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="font-body text-lg font-semibold text-gray-900">
                            {notification.title}
                          </h3>
                          {getPriorityBadge(notification.priority)}
                          {!notification.read && (
                            <div className="w-2 h-2 bg-[#3F5CEA] rounded-full"></div>
                          )}
                        </div>
                        <p className="font-body text-lg text-gray-700 mb-2">
                          {notification.message}
                        </p>
                        <div className="flex items-center gap-1 text-lg text-gray-500">
                          <Clock className="h-4 w-4" />
                          <span>{getTimeAgo(notification.timestamp)}</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 ml-4">
                      {notification.actionUrl && (
                        <Button variant="outline" size="sm" asChild>
                          <a href={notification.actionUrl}>
                            <Eye className="h-4 w-4 mr-1" />
                            View
                          </a>
                        </Button>
                      )}
                      {!notification.read && (
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          onClick={() => markAsRead(notification.id)}
                        >
                          <EyeOff className="h-4 w-4" />
                        </Button>
                      )}
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => deleteNotification(notification.id)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </AnimatedCard>
            ))
          )}
        </TabsContent>
      </Tabs>

      {/* Notification Settings */}
      <AnimatedCard>
        <CardHeader>
          <CardTitle className="font-primary text-2xl flex items-center gap-2">
            <Settings className="h-5 w-5" />
            Notification Preferences
          </CardTitle>
          <p className="font-body text-lg text-gray-600">
            Customize how and when you receive notifications
          </p>
        </CardHeader>
        <CardContent>
          <div className="space-y-8">
            {/* Email Notifications */}
            <div>
              <h3 className="font-primary text-xl font-semibold text-gray-900 mb-4">Email Notifications</h3>
              <div className="space-y-4">
                {Object.entries(settings.emailNotifications).map(([key, value]) => (
                  <div key={key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div>
                      <label className="font-body text-lg font-medium text-gray-900 capitalize">
                        {key.replace(/([A-Z])/g, ' $1').toLowerCase()}
                      </label>
                      <p className="font-body text-lg text-gray-600">
                        {key === 'newReviews' && 'Get notified when families leave reviews'}
                        {key === 'contactInquiries' && 'Get notified when families contact you'}
                        {key === 'profileUpdates' && 'Get notified about profile changes'}
                        {key === 'systemUpdates' && 'Get notified about system announcements'}
                        {key === 'monthlyReports' && 'Receive monthly performance reports'}
                      </p>
                    </div>
                    <Button
                      variant={value ? "default" : "outline"}
                      size="sm"
                      onClick={() => toggleSetting("emailNotifications", key)}
                      className={value ? "bg-[#3F5CEA] hover:bg-[#2E4BC7]" : ""}
                    >
                      {value ? "Enabled" : "Disabled"}
                    </Button>
                  </div>
                ))}
              </div>
            </div>

            {/* Push Notifications */}
            <div>
              <h3 className="font-primary text-xl font-semibold text-gray-900 mb-4">Push Notifications</h3>
              <div className="space-y-4">
                {Object.entries(settings.pushNotifications).map(([key, value]) => (
                  <div key={key} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div>
                      <label className="font-body text-lg font-medium text-gray-900 capitalize">
                        {key.replace(/([A-Z])/g, ' $1').toLowerCase()}
                      </label>
                      <p className="font-body text-lg text-gray-600">
                        {key === 'newReviews' && 'Instant browser notifications for new reviews'}
                        {key === 'contactInquiries' && 'Instant notifications for contact inquiries'}
                        {key === 'profileUpdates' && 'Notifications for profile changes'}
                        {key === 'systemUpdates' && 'Notifications for system announcements'}
                        {key === 'monthlyReports' && 'Notifications when reports are ready'}
                      </p>
                    </div>
                    <Button
                      variant={value ? "default" : "outline"}
                      size="sm"
                      onClick={() => toggleSetting("pushNotifications", key)}
                      className={value ? "bg-[#3F5CEA] hover:bg-[#2E4BC7]" : ""}
                    >
                      {value ? "Enabled" : "Disabled"}
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CardContent>
      </AnimatedCard>
    </div>
  )
}
