"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { submitPartnerLead, type PartnerLeadInput } from "./actions";
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";
import { COUNTRIES } from "@/lib/constants";

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

export function SubmitLeadForm() {
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [country, setCountry] = useState("");
  const [countrySearch, setCountrySearch] = useState("");
  const [city, setCity] = useState("");
  const [preferredCountry, setPreferredCountry] = useState("");
  const [prefCountrySearch, setPrefCountrySearch] = useState("");
  const [comments, setComments] = useState("");

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

    const payload: PartnerLeadInput = {
      full_name: fullName,
      phone,
      email,
      country,
      city,
      preferred_country: preferredCountry,
      comments,
    };

    startTransition(async () => {
      const res = await submitPartnerLead(payload);
      if (res.error) {
        toast.error(res.error);
        return;
      }
      toast.success("Lead submitted");
      router.push("/partner/leads");
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Lead Details</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 htmlFor="phone">Phone</Label>
            <Input
              id="phone"
              value={phone}
              onChange={(e) => setPhone(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 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>
          <div className="space-y-2">
            <Label htmlFor="city">City</Label>
            <Input
              id="city"
              value={city}
              onChange={(e) => setCity(e.target.value)}
            />
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label>Preferred country</Label>
            <Select value={preferredCountry || NONE} onValueChange={(v) => setPreferredCountry(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={prefCountrySearch} 
                    onChange={(e) => setPrefCountrySearch(e.target.value)} 
                    onKeyDown={(e) => e.stopPropagation()}
                  />
                </div>
                <SelectItem value={NONE}>—</SelectItem>
                {COUNTRIES
                  .filter((c) => c.toLowerCase().includes(prefCountrySearch.toLowerCase()))
                  .map((c) => (
                  <SelectItem key={c} value={c}>
                    {c}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2 sm:col-span-2">
            <Label htmlFor="comments">Comments</Label>
            <textarea
              id="comments"
              className={textareaClass}
              value={comments}
              onChange={(e) => setComments(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end gap-3">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.push("/partner/leads")}
          disabled={pending}
        >
          Cancel
        </Button>
        <Button
          type="submit"
          disabled={pending}
          className="bg-brand-orange hover:bg-brand-orange/90"
        >
          {pending ? "Submitting…" : "Submit lead"}
        </Button>
      </div>
    </form>
  );
}
