"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Pencil, Plus } from "lucide-react";
import {
  createInstitute,
  updateInstitute,
  toggleInstituteActive,
} from "./actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import type { Country, Institute, State } from "@/lib/types";

const NONE = "__none__";

export function InstituteRowToggle({ id, isActive }: { id: string; isActive: boolean }) {
  const [pending, start] = useTransition();
  return (
    <Switch
      checked={isActive}
      disabled={pending}
      onCheckedChange={(next) =>
        start(async () => {
          await toggleInstituteActive(id, next);
          toast.success(next ? "Activated" : "Deactivated");
        })
      }
    />
  );
}

export function InstituteDialog({
  countries,
  states,
  institute,
}: {
  countries: Country[];
  states: State[];
  institute?: Institute;
}) {
  const editing = !!institute;
  const [open, setOpen] = useState(false);
  const [countryId, setCountryId] = useState(institute?.country_id ?? NONE);
  const [stateId, setStateId] = useState(institute?.state_id ?? NONE);
  const [isDirect, setIsDirect] = useState(institute?.is_direct ?? false);
  const [pending, startTransition] = useTransition();

  const action = editing ? updateInstitute : createInstitute;

  function onSubmit(formData: FormData) {
    startTransition(async () => {
      const res = await action(undefined, formData);
      if (res?.ok) {
        toast.success(editing ? "Institute updated" : "Institute created");
        setOpen(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  function handleOpenChange(next: boolean) {
    setOpen(next);
    if (next) {
      setCountryId(institute?.country_id ?? NONE);
      setStateId(institute?.state_id ?? NONE);
      setIsDirect(institute?.is_direct ?? false);
    }
  }

  // Filter states by selected country (states with matching country_id), keep all when none selected.
  const visibleStates =
    countryId && countryId !== NONE
      ? states.filter((s) => s.country_id === countryId)
      : states;

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        {editing ? (
          <Button size="icon" variant="ghost">
            <Pencil className="size-4" />
          </Button>
        ) : (
          <Button>
            <Plus className="size-4" /> Add Institute
          </Button>
        )}
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editing ? "Edit Institute" : "Add Institute"}</DialogTitle>
        </DialogHeader>
        <form action={onSubmit} className="grid grid-cols-2 gap-4">
          {editing && <input type="hidden" name="id" value={institute.id} />}
          <input type="hidden" name="country_id" value={countryId} />
          <input type="hidden" name="state_id" value={stateId} />
          <input type="hidden" name="is_direct" value={isDirect ? "true" : "false"} />

          <div className="col-span-2 space-y-2">
            <Label htmlFor="name">Institute name *</Label>
            <Input id="name" name="name" defaultValue={institute?.name} required />
          </div>

          <div className="space-y-2">
            <Label htmlFor="country_id">Country</Label>
            <Select
              value={countryId}
              onValueChange={(v) => {
                setCountryId(v);
                setStateId(NONE);
              }}
            >
              <SelectTrigger id="country_id">
                <SelectValue placeholder="Select country" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>None</SelectItem>
                {countries.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="state_id">State</Label>
            <Select value={stateId} onValueChange={setStateId}>
              <SelectTrigger id="state_id">
                <SelectValue placeholder="Select state" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NONE}>None</SelectItem>
                {visibleStates.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    {s.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="city">City</Label>
            <Input id="city" name="city" defaultValue={institute?.city ?? ""} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="logo_url">Logo URL</Label>
            <Input
              id="logo_url"
              name="logo_url"
              defaultValue={institute?.logo_url ?? ""}
              placeholder="https://…"
            />
          </div>

          <label className="col-span-2 flex items-center gap-2 text-sm">
            <Checkbox
              checked={isDirect}
              onCheckedChange={(c) => setIsDirect(c === true)}
            />
            Direct institute
          </label>

          <div className="col-span-2 flex justify-end">
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : editing ? "Save changes" : "Save institute"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
