"use client";
import clsx from "clsx";
import { ChangeEvent, useEffect, useRef, useState } from "react";
import { useFormState } from "react-dom";
import { Input } from "~/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select";
import { addSubRegion } from "~/server/actions/addSubRegion";
import SubmitButton from "../SubmitButton";
import { Check, CircleX } from "lucide-react";

type Region = {
  id: string;
  name: string;
  countryId: string;
};
type Country = {
  id: string;
  name: string;
};

export default function CreateSubRegionForm(props: {
  allRegions: Region[];
  allCountries: Country[];
}) {
  const { allRegions, allCountries } = props;
  const [selectCountryId, setSelectCountryId] = useState<string | undefined>(
    undefined,
  );
  const [selectCountryRegions, setSelectCountryRegions] = useState<Region[]>(
    [],
  );
  const [formState, formActions] = useFormState(addSubRegion, {
    message: "",
    errors: undefined,
    fieldValues: {
      name: "",
      regionId: "",
    },
  });

  useEffect(() => {
    if (selectCountryId) {
      const regions = allRegions.filter(
        (region) => region.countryId === selectCountryId,
      );
      setSelectCountryRegions(regions);
    }
  }, [selectCountryId]);

  const formRef = useRef<HTMLFormElement>(null);
  useEffect(() => {
    if (formState.message === "success") {
      formRef.current?.reset();
    }
  }, [formState.message]);
  return (
    <div className="flex flex-col gap-2">
      {/* country selector */}
      <Select
        name="country"
        onValueChange={(value) => setSelectCountryId(value)}
      >
        <SelectTrigger className={`w-[180px] `}>
          <SelectValue placeholder="select country" />
        </SelectTrigger>
        <SelectContent>
          {allCountries.map((country) => (
            <SelectItem key={country.id} value={country.id}>
              {country.name}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <form ref={formRef} action={formActions}>
        {/* region selector */}
        <div className="flex max-w-3xl items-center gap-2">
          <Select name="regionId">
            <SelectTrigger
              className={`w-[180px] ${clsx({ "border-red-500": formState.errors?.regionId })}`}
            >
              <SelectValue placeholder="select region" />
            </SelectTrigger>
            <SelectContent>
              {selectCountryRegions.map((region) => (
                <SelectItem key={region.id} value={region.id}>
                  {region.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {formState.message === "success" && !formState.errors?.regionId ? (
            <Check className="text-green-500" />
          ) : (
            ""
          )}
          {formState.errors?.regionId ? (
            <div className="flex min-w-40 items-center gap-1 text-red-500">
              <CircleX className="text-red-500" />
              <span className="text-sm">{formState.errors?.regionId}</span>
            </div>
          ) : (
            ""
          )}
        </div>
        <div className="flex max-w-3xl items-center gap-2">
          <Input
            name="name"
            id="name"
            placeholder="Name the sub region"
            className={`${clsx({ "border-red-500": formState.errors?.name })}`}
          />
          {formState.message === "success" && !formState.errors?.name ? (
            <Check className="text-green-500" />
          ) : (
            ""
          )}
          {formState.errors?.name ? (
            <div className="flex min-w-40 items-center gap-1 text-red-500">
              <CircleX className="text-red-500" />
              <span className="text-sm">{formState.errors?.name}</span>
            </div>
          ) : (
            ""
          )}
        </div>
        <SubmitButton text={"sub region"} />
      </form>
    </div>
  );
}
