import { Bell, CheckCircle, Mail, TrendingUp } from 'lucide-react';

import { Suspense, lazy } from 'react';

import { Head, Link, useForm } from '@inertiajs/react';

import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { Textarea } from '@/Components/ui/textarea';
import AdminLayout from '@/Layouts/AdminLayout';
import { formatRelativeTime } from '@/lib/format';
import type { AdminNotificationsDashboardProps } from '@/types/admin';

// Chart loading fallback
const ChartLoader = () => (
  <div className="h-[250px] rounded-lg border bg-card p-4 space-y-3">
    <Skeleton className="h-5 w-40" />
    <Skeleton className="h-[200px] w-full" />
  </div>
);

// Lazy load volume area chart
const LazyVolumeChart = lazy(async () => {
  const { AreaChart, Area, CartesianGrid, ChartContainer, ChartTooltip, XAxis, YAxis } =
    await import('@/Components/ui/chart');
  return {
    default: ({ data }: { data: { date: string; count: number }[] }) => (
      <ChartContainer height={250}>
        <AreaChart data={data}>
          <defs>
            <linearGradient id="notifGradient" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.3} />
              <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis
            dataKey="date"
            tickFormatter={(v) =>
              new Date(v).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
            }
            className="text-xs"
          />
          <YAxis allowDecimals={false} className="text-xs" />
          <ChartTooltip />
          <Area
            type="monotone"
            dataKey="count"
            name="Sent"
            stroke="hsl(var(--primary))"
            fill="url(#notifGradient)"
            strokeWidth={2}
          />
        </AreaChart>
      </ChartContainer>
    ),
  };
});

// Lazy load by type bar chart
const LazyTypeChart = lazy(async () => {
  const { BarChart, Bar, CartesianGrid, ChartContainer, ChartTooltip, XAxis, YAxis, CHART_COLORS } =
    await import('@/Components/ui/chart');
  return {
    default: ({ data }: { data: { type: string; count: number }[] }) => (
      <ChartContainer height={250}>
        <BarChart data={data}>
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis dataKey="type" className="text-xs" />
          <YAxis allowDecimals={false} className="text-xs" />
          <ChartTooltip />
          <Bar dataKey="count" name="Count" fill={CHART_COLORS[0]} radius={[4, 4, 0, 0]} />
        </BarChart>
      </ChartContainer>
    ),
  };
});

export default function NotificationsDashboard({
  stats,
  volume_chart,
  recent_notifications,
}: AdminNotificationsDashboardProps) {
  const form = useForm({
    title: '',
    body: '',
    type: 'info' as string,
    segment: 'all' as string,
  });

  function handleBroadcast(e: React.FormEvent) {
    e.preventDefault();
    form.post(route('admin.notifications.broadcast'));
  }

  return (
    <AdminLayout>
      <Head title="Admin - Notifications" />
      <PageHeader title="Notifications" description="Delivery stats and read rates" />

      <div className="container py-6 space-y-6">
        {/* Stats */}
        <AdminStatsGrid
          stats={
            [
              { title: 'Total Sent', value: stats.total_sent, icon: Mail },
              { title: 'Unread', value: stats.unread, icon: Bell },
              {
                title: 'Read Rate',
                value: stats.read_rate,
                icon: CheckCircle,
                format: (n) => `${n}%`,
              },
              { title: 'Sent Last 7d', value: stats.sent_last_7d, icon: TrendingUp },
            ] satisfies StatCard[]
          }
        />

        <div className="grid gap-6 md:grid-cols-2">
          {/* Volume Chart */}
          <Card>
            <CardHeader>
              <CardTitle>Notification Volume (14d)</CardTitle>
              <CardDescription>Notifications sent per day</CardDescription>
            </CardHeader>
            <CardContent>
              {volume_chart.length === 0 ? (
                <EmptyState
                  icon={Mail}
                  title="No data yet"
                  description="Notification volume will appear here."
                  size="sm"
                  animated={false}
                />
              ) : (
                <ChartErrorBoundary>
                  <Suspense fallback={<ChartLoader />}>
                    <LazyVolumeChart data={volume_chart} />
                  </Suspense>
                </ChartErrorBoundary>
              )}
            </CardContent>
          </Card>

          {/* By Type */}
          <Card>
            <CardHeader>
              <CardTitle>By Type</CardTitle>
              <CardDescription>Notifications grouped by type</CardDescription>
            </CardHeader>
            <CardContent>
              {stats.by_type.length === 0 ? (
                <EmptyState
                  icon={Bell}
                  title="No data"
                  description="Type breakdown will appear here."
                  size="sm"
                  animated={false}
                />
              ) : (
                <ChartErrorBoundary>
                  <Suspense fallback={<ChartLoader />}>
                    <LazyTypeChart data={stats.by_type} />
                  </Suspense>
                </ChartErrorBoundary>
              )}
            </CardContent>
          </Card>
        </div>
        {/* Broadcast Form */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Send Broadcast Notification</CardTitle>
            <CardDescription>Notify a segment of users. Rate limited to 1 broadcast per hour.</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleBroadcast} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="broadcast-title">Title</Label>
                <Input
                  id="broadcast-title"
                  value={form.data.title}
                  onChange={(e) => form.setData('title', e.target.value)}
                  placeholder="Notification title"
                  required
                />
                {form.errors.title && <p className="text-sm text-destructive">{form.errors.title}</p>}
              </div>
              <div className="space-y-2">
                <Label htmlFor="broadcast-body">Body</Label>
                <Textarea
                  id="broadcast-body"
                  value={form.data.body}
                  onChange={(e) => form.setData('body', e.target.value)}
                  placeholder="Notification body text"
                  rows={3}
                  required
                />
                {form.errors.body && <p className="text-sm text-destructive">{form.errors.body}</p>}
              </div>
              <div className="flex gap-4">
                <div className="space-y-2 flex-1">
                  <Label>Type</Label>
                  <Select value={form.data.type} onValueChange={(v) => form.setData('type', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="info">Info</SelectItem>
                      <SelectItem value="success">Success</SelectItem>
                      <SelectItem value="warning">Warning</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2 flex-1">
                  <Label>Segment</Label>
                  <Select value={form.data.segment} onValueChange={(v) => form.setData('segment', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Users</SelectItem>
                      <SelectItem value="active">Active (last 30 days)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <LoadingButton type="submit" loading={form.processing} className="w-full">
                Send Broadcast
              </LoadingButton>
            </form>
          </CardContent>
        </Card>

        {/* Recent Notifications */}
        <Card>
          <CardHeader>
            <CardTitle>Recent Notifications</CardTitle>
            <CardDescription>Latest notifications sent to users</CardDescription>
          </CardHeader>
          <CardContent className="p-0">
            {recent_notifications.length === 0 ? (
              <EmptyState
                icon={Bell}
                title="No notifications yet"
                description="Recent notifications will appear here."
                size="sm"
                animated={false}
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>User</TableHead>
                      <TableHead>Type</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Sent</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {recent_notifications.map((n, i) => (
                      <TableRow key={`${n.user_id}-${n.created_at}-${i}`}>
                        <TableCell>
                          <Link href={`/admin/users/${n.user_id}`} className="font-medium hover:underline">
                            {n.user_name}
                          </Link>
                          <div className="text-xs text-muted-foreground">{n.user_email}</div>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">{n.type}</TableCell>
                        <TableCell>
                          {n.read_at ? (
                            <Badge variant="secondary">Read</Badge>
                          ) : (
                            <Badge variant="outline">Unread</Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatRelativeTime(n.created_at)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </AdminLayout>
  );
}
