import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Calendar as CalendarComponent } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { format } from "date-fns";
import { CalendarIcon, Plus, Copy, Repeat, Users, Clock, MapPin, AlertCircle, Check, X, Search, Filter } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { type Team } from "@shared/schema";
import { z } from "zod";
import { cn } from "@/lib/utils";

const activityFormSchema = z.object({
  title: z.string().min(1, "Title is required"),
  description: z.string().optional(),
  type: z.enum(["training", "match", "meeting", "event"]),
  date: z.date(),
  startTime: z.string(),
  endTime: z.string(),
  location: z.string().optional(),
  teamId: z.number().optional(),
  departmentId: z.number().optional(),
  isRecurring: z.boolean().default(false),
  recurringUntil: z.date().optional(),
  recurringFrequency: z.enum(["daily", "weekly", "monthly"]).optional(),
  recurringDays: z.array(z.number()).optional(),
});

type ActivityFormData = z.infer<typeof activityFormSchema>;
type Activity = ActivityFormData & { id: number; createdAt: Date; updatedAt: Date; };

export default function CalendarPage() {
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [viewMode, setViewMode] = useState<"month" | "week" | "day">("month");
  const [filterType, setFilterType] = useState<"all" | "training" | "match" | "meeting" | "social">("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [showActivityForm, setShowActivityForm] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);
  
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Fetch activities
  const { data: activities = [], isLoading: activitiesLoading } = useQuery<Activity[]>({
    queryKey: ["/api/activities"],
  });

  // Fetch teams
  const { data: teams = [] } = useQuery<Team[]>({
    queryKey: ["/api/teams"],
  });

  const activityForm = useForm<ActivityFormData>({
    resolver: zodResolver(activityFormSchema),
    defaultValues: {
      title: "",
      description: "",
      type: "training",
      location: "",
      date: new Date(),
      startTime: "",
      endTime: "",
      isRecurring: false,
    },
  });

  // Create activity mutation
  const createActivityMutation = useMutation({
    mutationFn: async (data: ActivityFormData) => {
      const activityData = {
        ...data,
        startDateTime: new Date(`${format(selectedDate, "yyyy-MM-dd")}T${data.startTime}`),
        endDateTime: new Date(`${format(selectedDate, "yyyy-MM-dd")}T${data.endTime}`),
        recurringPattern: data.isRecurring ? {
          frequency: data.recurringFrequency,
          days: data.recurringDays,
          endDate: data.recurringUntil,
        } : null,
      };
      
      const res = await apiRequest("POST", "/api/activities", activityData);
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Activity created",
        description: "The activity has been added to the calendar.",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/activities"] });
      setShowActivityForm(false);
      activityForm.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to create activity",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  // Copy activity mutation
  const copyActivityMutation = useMutation({
    mutationFn: async ({ activityId, newDate }: { activityId: number; newDate: Date }) => {
      const res = await apiRequest("POST", `/api/activities/${activityId}/copy`, { newDate });
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Activity copied",
        description: "The activity has been duplicated successfully.",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/activities"] });
    },
  });

  // Update attendance mutation
  const updateAttendanceMutation = useMutation({
    mutationFn: async ({ attendanceId, status, reason }: { attendanceId: number; status: string; reason?: string }) => {
      const res = await apiRequest("PATCH", `/api/activity-attendance/${attendanceId}`, { status, absenceReason: reason });
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Attendance updated",
        description: "The attendance status has been recorded.",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/activities"] });
    },
  });

  const filteredActivities = activities.filter(activity => {
    const matchesType = filterType === "all" || activity.type === filterType;
    const matchesSearch = activity.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         activity.description?.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesType && matchesSearch;
  });

  const getActivityColor = (type: string) => {
    switch (type) {
      case "training": return "bg-blue-500";
      case "match": return "bg-red-500";
      case "meeting": return "bg-green-500";
      case "social": return "bg-purple-500";
      default: return "bg-gray-500";
    }
  };

  const renderActivityForm = () => (
    <Dialog open={showActivityForm} onOpenChange={setShowActivityForm}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="h-4 w-4 mr-2" />
          Add Activity
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Create New Activity</DialogTitle>
          <DialogDescription>
            Schedule a new activity for your rugby club. You can target specific teams, departments, or the entire club.
          </DialogDescription>
        </DialogHeader>

        <Form {...activityForm}>
          <form onSubmit={activityForm.handleSubmit((data) => createActivityMutation.mutate(data))} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={activityForm.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Activity Title</FormLabel>
                    <FormControl>
                      <Input placeholder="e.g., Training Session" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={activityForm.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Activity Type</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="training">Training</SelectItem>
                        <SelectItem value="match">Match</SelectItem>
                        <SelectItem value="meeting">Meeting</SelectItem>
                        <SelectItem value="social">Social Event</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={activityForm.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea placeholder="Activity details..." {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <FormField
                control={activityForm.control}
                name="startTime"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Start Time</FormLabel>
                    <FormControl>
                      <Input type="time" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={activityForm.control}
                name="endTime"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>End Time</FormLabel>
                    <FormControl>
                      <Input type="time" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={activityForm.control}
                name="location"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Location</FormLabel>
                    <FormControl>
                      <Input placeholder="Training ground" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Targeting Options */}
            <div className="space-y-4">
              <Label className="text-base font-semibold">Target Audience</Label>
              
              <FormField
                control={activityForm.control}
                name="clubWide"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>Entire Club</FormLabel>
                      <FormDescription>
                        Make this activity available to all club members
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              {!activityForm.watch("clubWide") && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>Departments</Label>
                    <div className="space-y-2 mt-2">
                      {departments.map((dept) => (
                        <div key={dept.id} className="flex items-center space-x-2">
                          <Checkbox
                            id={`dept-${dept.id}`}
                            checked={activityForm.watch("departmentIds")?.includes(dept.id) || false}
                            onCheckedChange={(checked) => {
                              const current = activityForm.getValues("departmentIds") || [];
                              if (checked) {
                                activityForm.setValue("departmentIds", [...current, dept.id]);
                              } else {
                                activityForm.setValue("departmentIds", current.filter(id => id !== dept.id));
                              }
                            }}
                          />
                          <Label htmlFor={`dept-${dept.id}`} className="text-sm">
                            {dept.name}
                          </Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div>
                    <Label>Teams</Label>
                    <div className="space-y-2 mt-2">
                      {teams.map((team) => (
                        <div key={team.id} className="flex items-center space-x-2">
                          <Checkbox
                            id={`team-${team.id}`}
                            checked={activityForm.watch("teamIds")?.includes(team.id) || false}
                            onCheckedChange={(checked) => {
                              const current = activityForm.getValues("teamIds") || [];
                              if (checked) {
                                activityForm.setValue("teamIds", [...current, team.id]);
                              } else {
                                activityForm.setValue("teamIds", current.filter(id => id !== team.id));
                              }
                            }}
                          />
                          <Label htmlFor={`team-${team.id}`} className="text-sm">
                            {team.name}
                          </Label>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Recurring Options */}
            <div className="space-y-4">
              <FormField
                control={activityForm.control}
                name="isRecurring"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>Recurring Activity</FormLabel>
                      <FormDescription>
                        Repeat this activity on a schedule
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              {activityForm.watch("isRecurring") && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <FormField
                    control={activityForm.control}
                    name="recurringFrequency"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Frequency</FormLabel>
                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="daily">Daily</SelectItem>
                            <SelectItem value="weekly">Weekly</SelectItem>
                            <SelectItem value="monthly">Monthly</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={activityForm.control}
                    name="recurringUntil"
                    render={({ field }) => (
                      <FormItem className="flex flex-col">
                        <FormLabel>Repeat Until</FormLabel>
                        <Popover>
                          <PopoverTrigger asChild>
                            <FormControl>
                              <Button
                                variant="outline"
                                className={cn(
                                  "w-full pl-3 text-left font-normal",
                                  !field.value && "text-muted-foreground"
                                )}
                              >
                                {field.value ? (
                                  format(field.value, "PPP")
                                ) : (
                                  <span>Pick a date</span>
                                )}
                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                              </Button>
                            </FormControl>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0" align="start">
                            <CalendarComponent
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              disabled={(date) =>
                                date < new Date()
                              }
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              )}
            </div>

            {/* Additional Options */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={activityForm.control}
                name="isCompulsory"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>Compulsory Attendance</FormLabel>
                    </div>
                  </FormItem>
                )}
              />

              <FormField
                control={activityForm.control}
                name="weather"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Weather Dependency</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="indoor">Indoor</SelectItem>
                        <SelectItem value="outdoor">Outdoor</SelectItem>
                        <SelectItem value="weather-dependent">Weather Dependent</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setShowActivityForm(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={createActivityMutation.isPending}>
                {createActivityMutation.isPending ? "Creating..." : "Create Activity"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Club Calendar</h1>
          <p className="text-gray-600">Manage activities, training sessions, and events</p>
        </div>
        {renderActivityForm()}
      </div>

      {/* Filters and Search */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col md:flex-row gap-4 items-center">
            <div className="flex items-center space-x-2">
              <Search className="h-4 w-4" />
              <Input
                placeholder="Search activities..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-64"
              />
            </div>

            <div className="flex items-center space-x-2">
              <Filter className="h-4 w-4" />
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Activities</SelectItem>
                  <SelectItem value="training">Training</SelectItem>
                  <SelectItem value="match">Matches</SelectItem>
                  <SelectItem value="meeting">Meetings</SelectItem>
                  <SelectItem value="social">Social Events</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center space-x-1">
              <Button
                variant={viewMode === "month" ? "default" : "outline"}
                size="sm"
                onClick={() => setViewMode("month")}
              >
                Month
              </Button>
              <Button
                variant={viewMode === "week" ? "default" : "outline"}
                size="sm"
                onClick={() => setViewMode("week")}
              >
                Week
              </Button>
              <Button
                variant={viewMode === "day" ? "default" : "outline"}
                size="sm"
                onClick={() => setViewMode("day")}
              >
                Day
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Calendar Component */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="text-lg">Calendar</CardTitle>
          </CardHeader>
          <CardContent>
            <CalendarComponent
              mode="single"
              selected={selectedDate}
              onSelect={(date) => date && setSelectedDate(date)}
              className="rounded-md border"
            />
          </CardContent>
        </Card>

        {/* Activities List */}
        <Card className="lg:col-span-3">
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              Activities for {format(selectedDate, "MMMM d, yyyy")}
              <Badge variant="secondary">{filteredActivities.length} activities</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {activitiesLoading ? (
              <div className="space-y-4">
                {[...Array(3)].map((_, i) => (
                  <div key={i} className="animate-pulse">
                    <div className="h-24 bg-gray-200 rounded"></div>
                  </div>
                ))}
              </div>
            ) : filteredActivities.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <CalendarIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>No activities scheduled for this day.</p>
                <p className="text-sm">Use the "Add Activity" button to create one.</p>
              </div>
            ) : (
              <div className="space-y-4">
                {filteredActivities.map((activity) => (
                  <Card key={activity.id} className="hover:shadow-md transition-shadow">
                    <CardContent className="p-4">
                      <div className="flex items-start justify-between">
                        <div className="flex items-start space-x-3">
                          <div className={`w-3 h-3 rounded-full mt-2 ${getActivityColor(activity.activityType)}`} />
                          <div className="flex-1">
                            <div className="flex items-center space-x-2 mb-1">
                              <h3 className="font-semibold">{activity.title}</h3>
                              <Badge variant="outline" className="text-xs">
                                {activity.activityType}
                              </Badge>
                              {activity.isCompulsory && (
                                <Badge variant="destructive" className="text-xs">
                                  Required
                                </Badge>
                              )}
                              {activity.clubWide && (
                                <Badge variant="secondary" className="text-xs">
                                  Club Wide
                                </Badge>
                              )}
                            </div>
                            
                            <div className="flex items-center space-x-4 text-sm text-gray-600 mb-2">
                              <div className="flex items-center space-x-1">
                                <Clock className="h-4 w-4" />
                                <span>
                                  {format(new Date(activity.startDateTime), "HH:mm")} - 
                                  {format(new Date(activity.endDateTime), "HH:mm")}
                                </span>
                              </div>
                              {activity.location && (
                                <div className="flex items-center space-x-1">
                                  <MapPin className="h-4 w-4" />
                                  <span>{activity.location}</span>
                                </div>
                              )}
                            </div>

                            {activity.description && (
                              <p className="text-sm text-gray-600 mb-2">{activity.description}</p>
                            )}

                            {activity.isRecurring && (
                              <div className="flex items-center space-x-1 text-xs text-blue-600">
                                <Repeat className="h-3 w-3" />
                                <span>Recurring activity</span>
                              </div>
                            )}
                          </div>
                        </div>

                        <div className="flex items-center space-x-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => copyActivityMutation.mutate({ 
                              activityId: activity.id, 
                              newDate: new Date(selectedDate.getTime() + 7 * 24 * 60 * 60 * 1000) 
                            })}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => setSelectedActivity(activity)}
                          >
                            <Users className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}