"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  createCoachingApplication,
  updateCoachingApplication,
  type CoachingFormInput,
} from "./actions";
import type { CoachingOptions } from "@/lib/applications/queries";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const NONE = "__none__";

const COACHING_STATUSES = ["Active", "Completed", "Dropped"] as const;

export function CoachingForm({
  options,
  defaults,
  applicationId,
}: {
  options: CoachingOptions;
  defaults?: Partial<Record<string, unknown>>;
  applicationId?: string;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const d = (defaults ?? {}) as Record<string, unknown>;
  const str = (k: string) => (d[k] != null ? String(d[k]) : "");

  const [studentName, setStudentName] = useState(str("student_name"));
  const [email, setEmail] = useState(str("email"));
  const [phone, setPhone] = useState(str("phone"));
  const [leadId, setLeadId] = useState(str("lead_id"));
  const [subjectId, setSubjectId] = useState(str("subject_id"));
  const [levelId, setLevelId] = useState(str("level_id"));
  const [facultyId, setFacultyId] = useState(str("faculty_id"));
  const [registerForId, setRegisterForId] = useState(str("register_for_id"));
  const [status, setStatus] = useState(str("status") || "Active");
  const [fees, setFees] = useState(str("fees"));
  const [startDate, setStartDate] = useState(str("start_date"));
  const [branchId, setBranchId] = useState(str("branch_id"));

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!studentName.trim()) {
      toast.error("Student name is required");
      return;
    }

    const payload: CoachingFormInput = {
      student_name: studentName,
      branch_id: branchId,
      email,
      phone,
      lead_id: leadId,
      subject_id: subjectId,
      level_id: levelId,
      faculty_id: facultyId,
      register_for_id: registerForId,
      status,
      fees,
      start_date: startDate,
    };

    startTransition(async () => {
      const res = applicationId
        ? await updateCoachingApplication(applicationId, payload)
        : await createCoachingApplication(payload);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      toast.success(
        applicationId ? "Coaching application updated" : "Coaching application created",
      );
      router.push(
        res.id ? `/applications/coaching/${res.id}` : "/applications/coaching",
      );
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Student */}
      <Card>
        <CardHeader>
          <CardTitle>Student</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="student_name">Student name *</Label>
            <Input
              id="student_name"
              value={studentName}
              onChange={(e) => setStudentName(e.target.value)}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone">Phone</Label>
            <Input
              id="phone"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
            />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label>Linked lead</Label>
            <Select
              value={leadId || NONE}
              onValueChange={(v) => setLeadId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select lead" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.leads.map((l) => (
                  <SelectItem key={l.id} value={l.id}>
                    {l.full_name}
                    {l.phone ? ` · ${l.phone}` : ""}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Coaching */}
      <Card>
        <CardHeader>
          <CardTitle>Coaching</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Subject</Label>
            <Select
              value={subjectId || NONE}
              onValueChange={(v) => setSubjectId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select subject" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.subjects.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    {s.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Level</Label>
            <Select
              value={levelId || NONE}
              onValueChange={(v) => setLevelId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select level" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.levels.map((l) => (
                  <SelectItem key={l.id} value={l.id}>
                    {l.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Faculty</Label>
            <Select
              value={facultyId || NONE}
              onValueChange={(v) => setFacultyId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select faculty" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.faculty.map((f) => (
                  <SelectItem key={f.id} value={f.id}>
                    {f.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Register for</Label>
            <Select
              value={registerForId || NONE}
              onValueChange={(v) => setRegisterForId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select option" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.registerFor.map((r) => (
                  <SelectItem key={r.id} value={r.id}>
                    {r.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Status</Label>
            <Select value={status} onValueChange={setStatus}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                {COACHING_STATUSES.map((s) => (
                  <SelectItem key={s} value={s}>
                    {s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="fees">Fees</Label>
            <Input
              id="fees"
              type="number"
              min={0}
              step="0.01"
              value={fees}
              onChange={(e) => setFees(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="start_date">Start date</Label>
            <Input
              id="start_date"
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>Branch</Label>
            <Select
              value={branchId || NONE}
              onValueChange={(v) => setBranchId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Default branch" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.branches.map((b) => (
                  <SelectItem key={b.id} value={b.id}>
                    {b.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end gap-3">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.push("/applications/coaching")}
          disabled={pending}
        >
          Cancel
        </Button>
        <Button type="submit" disabled={pending}>
          {pending
            ? "Saving…"
            : applicationId
              ? "Update application"
              : "Create application"}
        </Button>
      </div>
    </form>
  );
}
