"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { createLead, updateLead, type LeadFormInput } from "./actions";
import type { LeadFormOptions } from "@/lib/leads/queries";
import { LEAD_STATUSES, GENDERS } from "@/lib/leads/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";
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuCheckboxItem,
} from "@/components/ui/dropdown-menu";
import { ChevronDown, Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";

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

interface LeadDefaults extends Partial<Record<string, unknown>> {
  branch_id?: string | null;
  lead_assignments?: { user_id: string }[] | null;
}

export function LeadForm({
  options,
  defaults,
  leadId,
}: {
  options: LeadFormOptions;
  defaults?: LeadDefaults;
  leadId?: 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]) : "");

  // Identity
  const [fullName, setFullName] = useState(str("full_name"));
  const [gender, setGender] = useState(str("gender"));
  const [dob, setDob] = useState(str("date_of_birth"));
  const [age, setAge] = useState(str("age"));

  // Contact
  const [phone, setPhone] = useState(str("phone"));
  const [altContact, setAltContact] = useState(str("alternate_contact"));
  const [email, setEmail] = useState(str("email"));
  const [country, setCountry] = useState(str("country"));
  const [countrySearch, setCountrySearch] = useState("");
  const [city, setCity] = useState(str("city"));

  // Interest
  const [inquiryId, setInquiryId] = useState(str("inquiry_id"));
  const [courseId, setCourseId] = useState(str("interested_course_id"));
  const initialPreferred = str("preferred_country");
  const [preferredCountry, setPreferredCountry] = useState<string[]>(
    initialPreferred ? initialPreferred.split(",").map((s) => s.trim()) : []
  );
  const [prefCountrySearch, setPrefCountrySearch] = useState("");
  const [otherService, setOtherService] = useState(str("other_service"));

  // Status & Source
  const [leadStatus, setLeadStatus] = useState(str("lead_status") || "New");
  const [sourceId, setSourceId] = useState(str("lead_source_id"));
  const [sourceOfRef, setSourceOfRef] = useState(str("source_of_reference"));
  const [branchId, setBranchId] = useState(
    str("branch_id") || (defaults?.branch_id ?? "") || "",
  );
  const [officeUse, setOfficeUse] = useState(str("office_use_only"));

  // Notes
  const [comments, setComments] = useState(str("comments"));
  const [remarks, setRemarks] = useState(str("remarks"));

  // Assignment — Default to Admin user when creating a new lead
  const [assignees, setAssignees] = useState<string[]>(() => {
    const existing = (defaults?.lead_assignments ?? []).map((a) => a.user_id);
    if (existing.length > 0) return existing;
    if (defaults) return [];

    const adminUser = options.assignableUsers.find(
      (u) => u.is_admin || u.email === "admin@eduadvise.in" || u.full_name.toLowerCase().includes("admin"),
    );
    return adminUser ? [adminUser.id] : [];
  });

  // Follow-up
  const [followupDate, setFollowupDate] = useState("");
  const [followupTypeId, setFollowupTypeId] = useState("");
  const [fromTime, setFromTime] = useState("");
  const [toTime, setToTime] = useState("");

  function toggleAssignee(id: string, checked: boolean) {
    setAssignees((prev) =>
      checked ? [...new Set([...prev, id])] : prev.filter((x) => x !== id),
    );
  }

  function toggleCountry(name: string, checked: boolean) {
    setPreferredCountry((prev) => {
      if (checked) {
        if (prev.length >= 3) return prev;
        return [...prev, name];
      }
      return prev.filter((c) => c !== name);
    });
  }

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

    const payload: LeadFormInput = {
      full_name: fullName,
      branch_id: branchId,
      email,
      phone,
      alternate_contact: altContact,
      country,
      city,
      gender,
      date_of_birth: dob,
      age,
      lead_status: leadStatus,
      lead_source_id: sourceId,
      inquiry_id: inquiryId,
      interested_course_id: courseId,
      preferred_country: preferredCountry.join(", "),
      other_service: otherService,
      source_of_reference: sourceOfRef,
      office_use_only: officeUse,
      comments,
      remarks,
      assigned_user_ids: assignees,
      next_followup_date: followupDate,
      followup_type_id: followupTypeId,
      from_time: fromTime,
      to_time: toTime,
    };

    startTransition(async () => {
      const res = leadId
        ? await updateLead(leadId, payload)
        : await createLead(payload);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      toast.success(leadId ? "Lead updated" : "Lead created");
      router.push(res.id ? `/leads/${res.id}` : "/leads");
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Identity */}
      <Card>
        <CardHeader>
          <CardTitle>Identity</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="full_name">Full name *</Label>
            <Input
              id="full_name"
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              required
            />
          </div>
          <div className="space-y-2">
            <Label>Gender</Label>
            <Select
              value={gender || NONE}
              onValueChange={(v) => setGender(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select gender" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {GENDERS.map((g) => (
                  <SelectItem key={g} value={g}>
                    {g}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="date_of_birth">Date of birth</Label>
            <Input
              id="date_of_birth"
              type="date"
              value={dob}
              onChange={(e) => {
                const val = e.target.value;
                setDob(val);
                if (val) {
                  const birth = new Date(val);
                  if (!isNaN(birth.getTime())) {
                    const today = new Date();
                    let calculatedAge = today.getFullYear() - birth.getFullYear();
                    const m = today.getMonth() - birth.getMonth();
                    if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
                      calculatedAge--;
                    }
                    setAge(calculatedAge.toString());
                  }
                } else {
                  setAge("");
                }
              }}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="age">Age</Label>
            <Input
              id="age"
              type="number"
              min={0}
              value={age}
              onChange={(e) => setAge(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Contact */}
      <Card>
        <CardHeader>
          <CardTitle>Contact</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <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 htmlFor="alternate_contact">Alternate contact</Label>
            <Input
              id="alternate_contact"
              value={altContact}
              onChange={(e) => setAltContact(e.target.value)}
            />
          </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>Country</Label>
            <Select value={country || NONE} onValueChange={(v) => setCountry(v === NONE ? "" : v)}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select country" />
              </SelectTrigger>
              <SelectContent>
                <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>
          <div className="space-y-2">
            <Label htmlFor="city">City</Label>
            <Input id="city" value={city} onChange={(e) => setCity(e.target.value)} />
          </div>
        </CardContent>
      </Card>

      {/* Interest */}
      <Card>
        <CardHeader>
          <CardTitle>Interest</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Inquiry</Label>
            <Select
              value={inquiryId || NONE}
              onValueChange={(v) => setInquiryId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select inquiry" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.inquiries.map((i) => (
                  <SelectItem key={i.id} value={i.id}>
                    {i.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Interested course</Label>
            <Select
              value={courseId || NONE}
              onValueChange={(v) => setCourseId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select course" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.interestedCourses.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Preferred country (up to 3)</Label>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button 
                  variant="outline" 
                  className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 font-normal"
                >
                  <span className="truncate">
                    {preferredCountry.length > 0
                      ? preferredCountry.join(", ")
                      : "Select countries..."}
                  </span>
                  <ChevronDown className="h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-(--radix-dropdown-menu-trigger-width) max-h-64 overflow-y-auto">
                <div className="p-2 sticky top-0 bg-popover z-10 border-b">
                  <Input 
                    placeholder="Search country..." 
                    value={prefCountrySearch} 
                    onChange={(e) => setPrefCountrySearch(e.target.value)} 
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                </div>
                {COUNTRIES
                  .filter((c) => c.toLowerCase().includes(prefCountrySearch.toLowerCase()))
                  .map((c) => (
                  <DropdownMenuCheckboxItem
                    key={c}
                    checked={preferredCountry.includes(c)}
                    onCheckedChange={(checked) => toggleCountry(c, checked === true)}
                    disabled={!preferredCountry.includes(c) && preferredCountry.length >= 3}
                    onSelect={(e) => e.preventDefault()}
                  >
                    {c}
                  </DropdownMenuCheckboxItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
          <div className="space-y-2">
            <Label htmlFor="other_service">Other service</Label>
            <Input
              id="other_service"
              value={otherService}
              onChange={(e) => setOtherService(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Status & Source */}
      <Card>
        <CardHeader>
          <CardTitle>Status &amp; Source</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label>Lead status</Label>
            <Select value={leadStatus} onValueChange={setLeadStatus}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                {LEAD_STATUSES.map((s) => (
                  <SelectItem key={s} value={s}>
                    {s}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Lead source</Label>
            <Select
              value={sourceId || NONE}
              onValueChange={(v) => setSourceId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select source" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.sources.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    {s.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="source_of_reference">Source of reference</Label>
            <Input
              id="source_of_reference"
              value={sourceOfRef}
              onChange={(e) => setSourceOfRef(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="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>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="office_use_only">Office use only</Label>
            <Input
              id="office_use_only"
              value={officeUse}
              onChange={(e) => setOfficeUse(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Notes */}
      <Card>
        <CardHeader>
          <CardTitle>Notes</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4">
          <div className="space-y-2">
            <Label htmlFor="comments">Comments</Label>
            <textarea
              id="comments"
              className={textareaClass}
              value={comments}
              onChange={(e) => setComments(e.target.value)}
            />
          </div>
          <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>

      {/* Assignment */}
      <Card>
        <CardHeader>
          <CardTitle>Assignment</CardTitle>
        </CardHeader>
        <CardContent>
          {options.assignableUsers.length === 0 ? (
            <p className="text-sm text-muted-foreground">No assignable users.</p>
          ) : (
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {options.assignableUsers.map((u) => (
                <label key={u.id} className="flex items-center gap-2 text-sm">
                  <Checkbox
                    checked={assignees.includes(u.id)}
                    onCheckedChange={(c) => toggleAssignee(u.id, c === true)}
                  />
                  {u.full_name}
                </label>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Follow-up */}
      <Card>
        <CardHeader>
          <CardTitle>Follow-up</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="next_followup_date">Next follow-up date</Label>
            <Input
              id="next_followup_date"
              type="date"
              value={followupDate}
              onChange={(e) => setFollowupDate(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>Follow-up type</Label>
            <Select
              value={followupTypeId || NONE}
              onValueChange={(v) => setFollowupTypeId(v === NONE ? "" : v)}
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>—</SelectItem>
                {options.followupTypes.map((f) => (
                  <SelectItem key={f.id} value={f.id}>
                    {f.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="from_time">From time</Label>
            <Input
              id="from_time"
              type="time"
              value={fromTime}
              onChange={(e) => setFromTime(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="to_time">To time</Label>
            <Input
              id="to_time"
              type="time"
              value={toTime}
              onChange={(e) => setToTime(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

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