"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { markAttendance } from "./actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

export interface AttendanceApplication {
  id: string;
  student_name: string;
  subject: { name: string } | null;
}

function todayStr() {
  return new Date().toISOString().slice(0, 10);
}

export function AttendanceClient({
  applications,
  initialApplicationId,
}: {
  applications: AttendanceApplication[];
  initialApplicationId?: string;
}) {
  const [pending, startTransition] = useTransition();
  const [appId, setAppId] = useState(
    initialApplicationId && applications.some((a) => a.id === initialApplicationId)
      ? initialApplicationId
      : "",
  );
  const [date, setDate] = useState(todayStr());
  const [currentStatus, setCurrentStatus] = useState<string | null>(null);

  // The displayed status reflects the last action taken in this session rather
  // than a fetched value, so clear it whenever the selection changes.
  function handleAppChange(next: string) {
    setAppId(next);
    setCurrentStatus(null);
  }

  function handleDateChange(next: string) {
    setDate(next);
    setCurrentStatus(null);
  }

  function submit(status: "present" | "absent") {
    if (!appId) {
      toast.error("Select a coaching application first");
      return;
    }
    startTransition(async () => {
      const res = await markAttendance(appId, date, status);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      setCurrentStatus(status);
      toast.success(`Marked ${status}`);
    });
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Mark attendance</CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {applications.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            No active coaching applications.
          </p>
        ) : (
          <>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>Coaching application</Label>
                <Select value={appId} onValueChange={handleAppChange}>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select application" />
                  </SelectTrigger>
                  <SelectContent>
                    {applications.map((a) => (
                      <SelectItem key={a.id} value={a.id}>
                        {a.student_name}
                        {a.subject?.name ? ` · ${a.subject.name}` : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="att_date">Date</Label>
                <Input
                  id="att_date"
                  type="date"
                  value={date}
                  onChange={(e) => handleDateChange(e.target.value)}
                />
              </div>
            </div>

            <div className="flex items-center gap-3">
              <Button
                type="button"
                onClick={() => submit("present")}
                disabled={pending || !appId}
              >
                Present
              </Button>
              <Button
                type="button"
                variant="destructive"
                onClick={() => submit("absent")}
                disabled={pending || !appId}
              >
                Absent
              </Button>
              {currentStatus && (
                <span className="text-sm text-muted-foreground">
                  Current:{" "}
                  <Badge
                    variant={currentStatus === "present" ? "default" : "destructive"}
                  >
                    {currentStatus}
                  </Badge>
                </span>
              )}
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
