"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  submitPartnerApplication,
  type PartnerApplicationInput,
} from "./actions";
import type { PartnerApplicationOptions } from "@/lib/applications/partner-queries";
import { COUNTRIES } from "@/lib/constants";
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 MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
] as const;

const textareaClass =
  "flex min-h-20 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]";

export function PartnerApplicationSubmitForm({
  options,
}: {
  options: PartnerApplicationOptions;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const [applicantName, setApplicantName] = useState("");
  const [phone, setPhone] = useState("");
  const [country, setCountry] = useState("");
  const [countrySearch, setCountrySearch] = useState("");
  const [instituteId, setInstituteId] = useState("");
  const [campusId, setCampusId] = useState("");
  const [courseId, setCourseId] = useState("");
  const [intakeMonth, setIntakeMonth] = useState("");
  const [intakeYear, setIntakeYear] = useState("");
  const [applicationTypeId, setApplicationTypeId] = useState("");
  const [remarks, setRemarks] = useState("");

  const filteredCourses = options.courses.filter(
    (c) => !instituteId || c.institute_id === instituteId,
  );

  function buildPayload(status: "Draft" | "Submitted"): PartnerApplicationInput {
    return {
      applicant_name: applicantName,
      phone: phone || undefined,
      country: country || undefined,
      institute_id: instituteId || undefined,
      campus_id: campusId || undefined,
      course_id: courseId || undefined,
      intake_month: intakeMonth || undefined,
      intake_year: intakeYear || undefined,
      application_type_id: applicationTypeId || undefined,
      remarks: remarks || undefined,
      status,
    };
  }

  function onSubmit(status: "Draft" | "Submitted") {
    startTransition(async () => {
      const res = await submitPartnerApplication(buildPayload(status));
      if (res.error) {
        toast.error(res.error);
        return;
      }
      toast.success(
        status === "Draft"
          ? "Application saved as draft"
          : "Application submitted to EduAdvise",
      );
      router.push(res.id ? `/partner/applications/${res.id}` : "/partner/applications");
    });
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Student details</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="applicant_name">Full name *</Label>
            <Input
              id="applicant_name"
              value={applicantName}
              onChange={(e) => setApplicantName(e.target.value)}
              required
            />
          </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">
            <Label>Country</Label>
            <Select value={country || NONE} onValueChange={(v) => setCountry(v === NONE ? "" : v)}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select country" />
              </SelectTrigger>
              <SelectContent position="popper">
                <div className="p-2 sticky top-0 bg-popover z-10 border-b">
                  <Input 
                    placeholder="Search country..." 
                    value={countrySearch} 
                    onChange={(e) => setCountrySearch(e.target.value)} 
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                </div>
                <SelectItem value={NONE}>—</SelectItem>
                {COUNTRIES
                  .filter((c) => c.toLowerCase().includes(countrySearch.toLowerCase()))
                  .map((c) => (
                  <SelectItem key={c} value={c}>
                    {c}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <p className="text-sm text-muted-foreground sm:col-span-2">
            Student email is added later by EduAdvise. The student will receive an
            invite to complete their profile.
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Course &amp; intake</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Institute</Label>
            <Select
              value={instituteId || NONE}
              onValueChange={(v) => {
                const next = v === NONE ? "" : v;
                setInstituteId(next);
                setCourseId("");
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select institute" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.institutes.map((i) => (
                  <SelectItem key={i.id} value={i.id}>
                    {i.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Campus</Label>
            <Select
              value={campusId || NONE}
              onValueChange={(v) => setCampusId(v === NONE ? "" : v)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select campus" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.campuses.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label>Course</Label>
            <Select
              value={courseId || NONE}
              onValueChange={(v) => setCourseId(v === NONE ? "" : v)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select course" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {filteredCourses.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.title}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Intake month</Label>
            <Select
              value={intakeMonth || NONE}
              onValueChange={(v) => setIntakeMonth(v === NONE ? "" : v)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Month" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {MONTHS.map((m) => (
                  <SelectItem key={m} value={m}>
                    {m}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="intake_year">Intake year</Label>
            <Input
              id="intake_year"
              type="number"
              min={2024}
              max={2035}
              value={intakeYear}
              onChange={(e) => setIntakeYear(e.target.value)}
            />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label>Application type</Label>
            <Select
              value={applicationTypeId || NONE}
              onValueChange={(v) => setApplicationTypeId(v === NONE ? "" : v)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.applicationTypes.map((t) => (
                  <SelectItem key={t.id} value={t.id}>
                    {t.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="remarks">Notes for EduAdvise</Label>
            <textarea
              id="remarks"
              className={textareaClass}
              value={remarks}
              onChange={(e) => setRemarks(e.target.value)}
              placeholder="Any context for the counseling team…"
            />
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        <Button
          type="button"
          variant="outline"
          disabled={pending}
          onClick={() => onSubmit("Draft")}
        >
          Save draft
        </Button>
        <Button
          type="button"
          className="bg-brand-orange hover:bg-brand-orange/90"
          disabled={pending}
          onClick={() => onSubmit("Submitted")}
        >
          {pending ? "Submitting…" : "Submit application"}
        </Button>
      </div>
    </div>
  );
}
