import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  useActivities,
  useActivityTypes,
  useCreateActivity,
  useDeleteActivity,
  useCreateActivityType,
  useDeleteActivityType,
  useStudents,
} from "@/hooks/queries";
import { Search, Plus, Trash2, Activity } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function AdminActivities() {
  const [search, setSearch] = useState("");
  const [section, setSection] = useState<"activities" | "types">("activities");
  const [actOpen, setActOpen] = useState(false);
  const [typeOpen, setTypeOpen] = useState(false);
  const [actForm, setActForm] = useState({ student_id: "", type_id: "", date: "", description: "" });
  const [typeName, setTypeName] = useState("");
  const { toast } = useToast();

  const actQ = useActivities();
  const typesQ = useActivityTypes();
  const { data: studentsData } = useStudents({ size: 500 });
  const studentsList = studentsData?.items ?? [];
  const createAct = useCreateActivity();
  const delAct = useDeleteActivity();
  const createType = useCreateActivityType();
  const delType = useDeleteActivityType();

  const loading = section === "activities" ? actQ.isLoading : typesQ.isLoading;
  const activities = actQ.data?.data ?? actQ.data?.items ?? [];
  const types = typesQ.data?.data ?? typesQ.data?.items ?? [];

  if (loading) {
    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>
    );
  }

  const q = search.toLowerCase();
  const filteredAct = activities.filter(
    (a) =>
      a.student_name?.toLowerCase().includes(q) ||
      a.type_name?.toLowerCase().includes(q) ||
      a.description?.toLowerCase().includes(q),
  );
  const filteredTypes = types.filter((t) => t.name?.toLowerCase().includes(q));

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Activity className="h-7 w-7" />
            Activities
          </h1>
          <p className="text-muted-foreground">Student activities and activity types.</p>
        </div>
        <Button
          onClick={() => (section === "activities" ? setActOpen(true) : setTypeOpen(true))}
        >
          <Plus className="mr-2 h-4 w-4" />
          {section === "activities" ? "New activity" : "New type"}
        </Button>
      </div>
      <div className="flex flex-wrap gap-2">
        <Button
          variant={section === "activities" ? "default" : "outline"}
          onClick={() => setSection("activities")}
        >
          Activities
        </Button>
        <Button variant={section === "types" ? "default" : "outline"} onClick={() => setSection("types")}>
          Activity types
        </Button>
      </div>
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      {section === "activities" ? (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Date</TableHead>
                  <TableHead>Description</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredAct.map((a, i) => (
                  <TableRow key={a.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{a.student_name}</TableCell>
                    <TableCell>{a.type_name}</TableCell>
                    <TableCell>{a.date}</TableCell>
                    <TableCell className="max-w-xs truncate">{a.description}</TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        variant="ghost"
                        className="text-destructive"
                        onClick={() => {
                          if (!window.confirm("Delete this activity?")) return;
                          delAct.mutate(a.id, {
                            onSuccess: () => toast({ title: "Deleted" }),
                            onError: (err: Error) =>
                              toast({ title: "Error", description: err.message, variant: "destructive" }),
                          });
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredTypes.map((t, i) => (
                  <TableRow key={t.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{t.name}</TableCell>
                    <TableCell>
                      <Button size="sm" variant="ghost" className="text-destructive" onClick={() => { if (!window.confirm("Delete this activity type?")) return; delType.mutate(t.id, { onSuccess: () => toast({ title: "Deleted" }), onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) }); }}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      <Dialog open={actOpen} onOpenChange={setActOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create activity</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Student *</Label>
              <Select value={actForm.student_id || "__none__"} onValueChange={(v) => setActForm((f) => ({ ...f, student_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select student" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {studentsList.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Activity Type *</Label>
              <Select value={actForm.type_id || "__none__"} onValueChange={(v) => setActForm((f) => ({ ...f, type_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {types.map((t) => <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Date</Label>
              <Input
                type="date"
                value={actForm.date}
                onChange={(e) => setActForm((f) => ({ ...f, date: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={actForm.description}
                onChange={(e) => setActForm((f) => ({ ...f, description: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setActOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={createAct.isPending || !actForm.student_id || !actForm.type_id || !actForm.date}
              onClick={() =>
                createAct.mutate(
                  {
                    student_id: Number(actForm.student_id),
                    type_id: Number(actForm.type_id),
                    date: actForm.date,
                    description: actForm.description || undefined,
                  },
                  {
                    onSuccess: () => {
                      setActOpen(false);
                      toast({ title: "Created successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                )
              }
            >
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={typeOpen} onOpenChange={setTypeOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create activity type</DialogTitle>
          </DialogHeader>
          <div className="space-y-2">
            <Label>Name</Label>
            <Input value={typeName} onChange={(e) => setTypeName(e.target.value)} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setTypeOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={createType.isPending}
              onClick={() =>
                createType.mutate(
                  { name: typeName },
                  {
                    onSuccess: () => {
                      setTypeOpen(false);
                      toast({ title: "Created successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                )
              }
            >
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
