"use client";

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

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

export function StateDialog({
  countries,
  state,
}: {
  countries: Country[];
  state?: State;
}) {
  const editing = !!state;
  const [open, setOpen] = useState(false);
  const [countryId, setCountryId] = useState(state?.country_id ?? "");
  const [pending, startTransition] = useTransition();
  const action = editing ? updateState : createState;

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

  function handleOpenChange(next: boolean) {
    setOpen(next);
    if (next) setCountryId(state?.country_id ?? "");
  }

  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 State
          </Button>
        )}
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editing ? "Edit State" : "Add State"}</DialogTitle>
        </DialogHeader>
        <form action={onSubmit} className="space-y-4">
          {editing && <input type="hidden" name="id" value={state.id} />}
          <div className="space-y-2">
            <Label htmlFor="name">State name *</Label>
            <Input id="name" name="name" defaultValue={state?.name} required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="country_id">Country *</Label>
            <input type="hidden" name="country_id" value={countryId} />
            <Select value={countryId} onValueChange={setCountryId}>
              <SelectTrigger id="country_id">
                <SelectValue placeholder="Select country" />
              </SelectTrigger>
              <SelectContent>
                {countries.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex justify-end">
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : editing ? "Save changes" : "Save state"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
