import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Pencil, Trash2, Loader2, Bell } from "lucide-react";
import { useNotificationRules, useCreateNotificationRule, useUpdateNotificationRule, useDeleteNotificationRule } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { NotificationChannel, ReminderFrequency, NotificationRule, NotificationRuleCreateRequest } from "@/types/notification";

export default function NotificationRules() {
  const { toast } = useToast();
  const { data: rules = [], isLoading } = useNotificationRules();
  const createRule = useCreateNotificationRule();
  const updateRule = useUpdateNotificationRule();
  const deleteRule = useDeleteNotificationRule();

  const [showForm, setShowForm] = useState(false);
  const [editingRule, setEditingRule] = useState<NotificationRule | null>(null);
  const [name, setName] = useState("");
  const [eventType, setEventType] = useState("");
  const [daysBefore, setDaysBefore] = useState(1);
  const [frequency, setFrequency] = useState<ReminderFrequency>("once");
  const [channel, setChannel] = useState<NotificationChannel>("in_app");

  const resetForm = () => { setName(""); setEventType(""); setDaysBefore(1); setFrequency("once"); setChannel("in_app"); setEditingRule(null); };

  const openEdit = (rule: NotificationRule) => {
    setEditingRule(rule);
    setName(rule.name);
    setEventType(rule.event_type);
    setDaysBefore(rule.days_before);
    setFrequency(rule.frequency);
    setChannel(rule.channel);
    setShowForm(true);
  };

  const handleSave = () => {
    const data = { name, event_type: eventType, days_before: daysBefore, frequency, channel };
    if (editingRule) {
      updateRule.mutate(
        { id: editingRule.id, data },
        {
          onSuccess: () => { toast({ title: "Rule Updated" }); setShowForm(false); resetForm(); },
          onError: () => toast({ title: "Error", description: "Failed to update rule", variant: "destructive" }),
        },
      );
    } else {
      createRule.mutate(data, {
        onSuccess: () => { toast({ title: "Rule Created" }); setShowForm(false); resetForm(); },
        onError: () => toast({ title: "Error", description: "Failed to create rule", variant: "destructive" }),
      });
    }
  };

  const handleDelete = (id: number) => {
    if (!window.confirm("Delete this notification rule?")) return;
    deleteRule.mutate(id, {
      onSuccess: () => toast({ title: "Rule Deleted" }),
      onError: () => toast({ title: "Error", description: "Failed to delete rule", variant: "destructive" }),
    });
  };

  const handleToggleActive = (rule: NotificationRule) => {
    updateRule.mutate(
      { id: rule.id, data: { active: !rule.active } as Partial<NotificationRuleCreateRequest> & { active?: boolean } },
      {
        onSuccess: () => toast({ title: rule.active ? "Rule Deactivated" : "Rule Activated" }),
        onError: () => toast({ title: "Error", description: "Failed to toggle rule", variant: "destructive" }),
      },
    );
  };

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Notification Rules</h1>
          <p className="text-muted-foreground">Configure automated notification rules and reminders.</p>
        </div>
        <Dialog open={showForm} onOpenChange={open => { setShowForm(open); if (!open) resetForm(); }}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Rule</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>{editingRule ? "Edit Rule" : "Create Notification Rule"}</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="Rule name" value={name} onChange={e => setName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Event Type</Label>
                <Select value={eventType} onValueChange={setEventType}>
                  <SelectTrigger><SelectValue placeholder="Select event" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="deadline">Deadline</SelectItem>
                    <SelectItem value="chapter_unlock">Chapter Unlock</SelectItem>
                    <SelectItem value="result_release">Result Release</SelectItem>
                    <SelectItem value="assignment">Assignment</SelectItem>
                    <SelectItem value="exam">Exam</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Days Before</Label>
                <Input type="number" min={0} value={daysBefore} onChange={e => setDaysBefore(Number(e.target.value))} />
              </div>
              <div className="space-y-2">
                <Label>Frequency</Label>
                <Select value={frequency} onValueChange={v => setFrequency(v as ReminderFrequency)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="once">Once</SelectItem>
                    <SelectItem value="daily">Daily</SelectItem>
                    <SelectItem value="custom">Custom</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Channel</Label>
                <Select value={channel} onValueChange={v => setChannel(v as NotificationChannel)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="in_app">In-App</SelectItem>
                    <SelectItem value="email">Email</SelectItem>
                    <SelectItem value="both">Both</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button className="w-full" onClick={handleSave} disabled={(createRule.isPending || updateRule.isPending) || !name || !eventType}>
                {(createRule.isPending || updateRule.isPending) && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {editingRule ? "Save Changes" : "Create Rule"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Event</TableHead>
              <TableHead>Days Before</TableHead>
              <TableHead>Frequency</TableHead>
              <TableHead>Channel</TableHead>
              <TableHead>Active</TableHead>
              <TableHead className="w-24">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rules.map(rule => (
              <TableRow key={rule.id}>
                <TableCell className="font-medium">{rule.name}</TableCell>
                <TableCell><Badge variant="outline">{rule.event_type}</Badge></TableCell>
                <TableCell>{rule.days_before}</TableCell>
                <TableCell>{rule.frequency}</TableCell>
                <TableCell><Badge variant="secondary">{rule.channel}</Badge></TableCell>
                <TableCell>
                  <Switch checked={rule.active} onCheckedChange={() => handleToggleActive(rule)} />
                </TableCell>
                <TableCell>
                  <div className="flex gap-1">
                    <Button variant="ghost" size="icon" onClick={() => openEdit(rule)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" onClick={() => handleDelete(rule.id)} disabled={deleteRule.isPending}>
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
            {rules.length === 0 && (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  <Bell className="h-12 w-12 mx-auto mb-3 opacity-40" />
                  <p>No notification rules configured.</p>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
