"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { completeStudentProfile } from "./actions";
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 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 OnboardingForm({
  applicationId,
  applicantName,
  defaults,
}: {
  applicationId: string;
  applicantName: string;
  defaults: {
    phone?: string | null;
    country?: string | null;
  };
}) {
  const [pending, startTransition] = useTransition();
  const [gender, setGender] = useState("");
  const [country, setCountry] = useState(defaults.country ?? "");
  const [countrySearch, setCountrySearch] = useState("");

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    if (!gender) {
      toast.error("Please select gender");
      return;
    }
    startTransition(async () => {
      const res = await completeStudentProfile({
        application_id: applicationId,
        phone: String(fd.get("phone") ?? ""),
        student_date_of_birth: String(fd.get("student_date_of_birth") ?? ""),
        student_gender: gender,
        student_city: String(fd.get("student_city") ?? ""),
        student_address: String(fd.get("student_address") ?? ""),
        country: String(fd.get("country") ?? ""),
      });
      if (res?.error) toast.error(res.error);
    });
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Complete profile — {applicantName}</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={onSubmit} className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="phone">Phone *</Label>
            <Input
              id="phone"
              name="phone"
              defaultValue={defaults.phone ?? ""}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="country">Country</Label>
            <Select name="country" value={country} onValueChange={setCountry}>
              <SelectTrigger id="country">
                <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>
                {COUNTRIES
                  .filter((c) => c.toLowerCase().includes(countrySearch.toLowerCase()))
                  .map((c) => (
                  <SelectItem key={c} value={c}>
                    {c}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="student_date_of_birth">Date of birth *</Label>
            <Input
              id="student_date_of_birth"
              name="student_date_of_birth"
              type="date"
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="student_gender">Gender *</Label>
            <Select value={gender} onValueChange={setGender} required>
              <SelectTrigger id="student_gender">
                <SelectValue placeholder="Select" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="Male">Male</SelectItem>
                <SelectItem value="Female">Female</SelectItem>
                <SelectItem value="Other">Other</SelectItem>
                <SelectItem value="Prefer not to say">Prefer not to say</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="student_city">City *</Label>
            <Input id="student_city" name="student_city" required />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="student_address">Address *</Label>
            <textarea
              id="student_address"
              name="student_address"
              className={textareaClass}
              required
            />
          </div>
          <div className="sm:col-span-2">
            <Button type="submit" disabled={pending} className="w-full sm:w-auto">
              {pending ? "Saving…" : "Complete profile & view application"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
