"use client";

import { useState, useEffect } from "react";
import { User, Client } from "@fitai/shared";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { useUser } from "@clerk/nextjs";
import log from "@/lib/logger";

interface ReportFiltersProps {
  selectedUserId: string;
  onUserChange: (userId: string) => void;
  dateRange: {
    startDate: string;
    endDate: string;
  };
  onDateRangeChange: (range: { startDate: string; endDate: string }) => void;
}

export function ReportFilters({
  selectedUserId,
  onUserChange,
  dateRange,
  onDateRangeChange,
}: ReportFiltersProps) {
  const { user: clerkUser } = useUser();
  const [users, setUsers] = useState<(User & { client?: Client | null })[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  useEffect(() => {
    fetchCurrentUserAndClients();
  }, []);

  const fetchCurrentUserAndClients = async () => {
    try {
      setLoading(true);

      const userResponse = await fetch("/api/users/me");
      if (!userResponse.ok) {
        setLoading(false);
        return;
      }

      const userData = await userResponse.json();
      setCurrentUser(userData.user);

      const currentRole = userData.user.role;
      let allUsers: (User & { client?: Client | null })[] = [];

      if (currentRole === "client") {
        setUsers([userData.user]);
        onUserChange(userData.user.id);
        setLoading(false);
        return;
      }

      if (currentRole === "trainer") {
        allUsers.push(userData.user);
        const assignmentsRes = await fetch("/api/trainer-client");
        if (assignmentsRes.ok) {
          const assignmentsData = await assignmentsRes.json();
          const assignedClientIds = (assignmentsData.assignments || [])
            .filter((a: any) => a.isActive)
            .map((a: any) => a.clientId);

          if (assignedClientIds.length > 0) {
            const clientsRes = await fetch(
              `/api/users?role=client&ids=${assignedClientIds.join(",")}`,
            );
            if (clientsRes.ok) {
              const clientsData = await clientsRes.json();
              allUsers = [...allUsers, ...(clientsData.data?.users || [])];
            }
          }
        }
        setUsers(allUsers);
        setLoading(false);
        return;
      }

      if (currentRole === "admin") {
        allUsers.push(userData.user);
      }

      if (currentRole === "superAdmin" || currentRole === "admin") {
        const [adminsRes, trainersRes, clientsRes] = await Promise.all([
          fetch("/api/users?role=admin"),
          fetch("/api/users?role=trainer"),
          fetch("/api/users?role=client"),
        ]);

        const [adminsData, trainersData, clientsData] = await Promise.all([
          adminsRes.ok ? adminsRes.json() : { data: { users: [] } },
          trainersRes.ok ? trainersRes.json() : { data: { users: [] } },
          clientsRes.ok ? clientsRes.json() : { data: { users: [] } },
        ]);

        allUsers = [
          ...allUsers,
          ...(adminsData.data?.users || []),
          ...(trainersData.data?.users || []),
          ...(clientsData.data?.users || []),
        ];

        if (currentRole === "superAdmin") {
          const superAdminsRes = await fetch("/api/users?role=superAdmin");
          if (superAdminsRes.ok) {
            const superAdminsData = await superAdminsRes.json();
            allUsers = [...(superAdminsData.data?.users || []), ...allUsers];
          }
        }

        setUsers(allUsers);
        setLoading(false);
        return;
      }

      setUsers(allUsers);
    } catch (error) {
      log.error("Failed to fetch users:", error);
    } finally {
      setLoading(false);
    }
  };

  const handlePresetRange = (days: number) => {
    const end = new Date();
    const start = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
    onDateRangeChange({
      startDate: start.toISOString().split("T")[0],
      endDate: end.toISOString().split("T")[0],
    });
  };

  return (
    <Card>
      <CardContent className="p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* User Selector */}
          <div className="space-y-2">
            <Label htmlFor="user-select">Select User</Label>
            <Select
              value={selectedUserId}
              onValueChange={onUserChange}
              disabled={loading}
            >
              <SelectTrigger id="user-select">
                <SelectValue placeholder="Choose a user..." />
              </SelectTrigger>
              <SelectContent>
                {users.map((user) => (
                  <SelectItem key={user.id} value={user.id}>
                    {user.firstName} {user.lastName} ({user.role})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Start Date */}
          <div className="space-y-2">
            <Label htmlFor="start-date">Start Date</Label>
            <input
              id="start-date"
              type="date"
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
              value={dateRange.startDate}
              onChange={(e) =>
                onDateRangeChange({
                  ...dateRange,
                  startDate: e.target.value,
                })
              }
            />
          </div>

          {/* End Date */}
          <div className="space-y-2">
            <Label htmlFor="end-date">End Date</Label>
            <input
              id="end-date"
              type="date"
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
              value={dateRange.endDate}
              onChange={(e) =>
                onDateRangeChange({
                  ...dateRange,
                  endDate: e.target.value,
                })
              }
            />
          </div>

          {/* Preset Ranges */}
          <div className="space-y-2">
            <Label>Quick Select</Label>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePresetRange(7)}
              >
                7 Days
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePresetRange(30)}
              >
                30 Days
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => handlePresetRange(90)}
              >
                90 Days
              </Button>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
