"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  createStudentApplication,
  updateStudentApplication,
  type ApplicationFormInput,
} from "./actions";
import type { StudentApplicationOptions } from "@/lib/applications/queries";
import { APPLICATION_STATUSES } from "@/lib/applications/constants";
import { COUNTRIES } from "@/lib/constants";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

const NONE = "__none__";

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]";

const MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
] as const;

interface ApplicationDefaults extends Partial<Record<string, unknown>> {
  branch_id?: string | null;
}

export function ApplicationForm({
  options,
  defaults,
  applicationId,
}: {
  options: StudentApplicationOptions;
  defaults?: ApplicationDefaults;
  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]) : "");

  // Applicant
  const [leadId, setLeadId] = useState(str("lead_id"));
  const [applicantName, setApplicantName] = useState(str("applicant_name"));
  const [email, setEmail] = useState(str("email"));
  const [phone, setPhone] = useState(str("phone"));
  const [country, setCountry] = useState(str("country"));
  const [countrySearch, setCountrySearch] = useState("");

  // Course
  const [instituteId, setInstituteId] = useState(str("institute_id"));
  const [campusId, setCampusId] = useState(str("campus_id"));
  const [intakeMonth, setIntakeMonth] = useState(str("intake_month"));
  const [intakeYear, setIntakeYear] = useState(str("intake_year"));

  // Application
  const [applicationTypeId, setApplicationTypeId] = useState(
    str("application_type_id"),
  );
  const [status, setStatus] = useState(str("status") || "Applied");
  const [counselorId, setCounselorId] = useState(str("counselor_id"));
  const [branchId, setBranchId] = useState(
    str("branch_id") || (defaults?.branch_id ?? "") || "",
  );

  // Offer & Fees
  const [offerReceived, setOfferReceived] = useState(
    d["offer_received"] === true,
  );
  const [offerDate, setOfferDate] = useState(str("offer_date"));
  const [tuitionFee, setTuitionFee] = useState(str("tuition_fee"));
  const [currency, setCurrency] = useState(str("currency") || "GBP");

  // Remarks
  const [remarks, setRemarks] = useState(str("remarks"));

  function onLeadChange(v: string) {
    const next = v === NONE ? "" : v;
    setLeadId(next);
    if (next) {
      const lead = options.leads.find((l) => l.id === next);
      if (lead) {
        if (lead.full_name) setApplicantName(lead.full_name);
        if (lead.phone) setPhone(lead.phone);
        if (lead.email) setEmail(lead.email);
      }
    }
  }

  // Status options: union of master statuses (preferred) and pipeline constants.
  const statusOptions =
    options.applicationStatuses.length > 0
      ? options.applicationStatuses.map((s) => s.name)
      : [...APPLICATION_STATUSES];

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

    const payload: ApplicationFormInput = {
      branch_id: branchId,
      applicant_name: applicantName,
      lead_id: leadId,
      email,
      phone,
      country,
      institute_id: instituteId,
      campus_id: campusId,
      intake_month: intakeMonth,
      intake_year: intakeYear,
      application_type_id: applicationTypeId,
      status,
      counselor_id: counselorId,
      offer_received: offerReceived,
      offer_date: offerDate,
      tuition_fee: tuitionFee,
      currency,
      remarks,
    };

    startTransition(async () => {
      const res = applicationId
        ? await updateStudentApplication(applicationId, payload)
        : await createStudentApplication(payload);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      toast.success(applicationId ? "Application updated" : "Application created");
      router.push(
        res.id ? `/applications/student/${res.id}` : "/applications/student",
      );
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Applicant */}
      <Card>
        <CardHeader>
          <CardTitle>Applicant</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2 sm:col-span-2">
            <Label>Linked lead</Label>
            <Select value={leadId || NONE} onValueChange={onLeadChange}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select lead (optional)" />
              </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>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="applicant_name">Applicant name *</Label>
            <Input
              id="applicant_name"
              value={applicantName}
              onChange={(e) => setApplicantName(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">
            <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>
        </CardContent>
      </Card>

      {/* Course */}
      <Card>
        <CardHeader>
          <CardTitle>Course</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Institute</Label>
            <Select
              value={instituteId || NONE}
              onValueChange={(v) => setInstituteId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <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 className="w-full">
                <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">
            <Label>Intake month</Label>
            <Select
              value={intakeMonth || NONE}
              onValueChange={(v) => setIntakeMonth(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select 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={2000}
              max={2100}
              value={intakeYear}
              onChange={(e) => setIntakeYear(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Application */}
      <Card>
        <CardHeader>
          <CardTitle>Application</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Application type</Label>
            <Select
              value={applicationTypeId || NONE}
              onValueChange={(v) => setApplicationTypeId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select 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">
            <Label>Status</Label>
            <Select value={status} onValueChange={setStatus}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                {statusOptions.map((s) => (
                  <SelectItem key={s} value={s}>
                    {s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Counselor</Label>
            <Select
              value={counselorId || NONE}
              onValueChange={(v) => setCounselorId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select counselor" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.counselors.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.full_name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </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="Select 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>

      {/* Offer & Fees */}
      <Card>
        <CardHeader>
          <CardTitle>Offer &amp; Fees</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2 sm:col-span-2">
            <label className="flex items-center gap-2 text-sm">
              <Checkbox
                checked={offerReceived}
                onCheckedChange={(c) => setOfferReceived(c === true)}
              />
              Offer received
            </label>
          </div>
          <div className="space-y-2">
            <Label htmlFor="offer_date">Offer date</Label>
            <Input
              id="offer_date"
              type="date"
              value={offerDate}
              onChange={(e) => setOfferDate(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="tuition_fee">Tuition fee</Label>
            <Input
              id="tuition_fee"
              type="number"
              min={0}
              step="0.01"
              value={tuitionFee}
              onChange={(e) => setTuitionFee(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="currency">Currency</Label>
            <Input
              id="currency"
              value={currency}
              onChange={(e) => setCurrency(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Remarks */}
      <Card>
        <CardHeader>
          <CardTitle>Remarks</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            <Label htmlFor="remarks">Remarks</Label>
            <textarea
              id="remarks"
              className={textareaClass}
              value={remarks}
              onChange={(e) => setRemarks(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

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