"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { ReactSelect } from "@/components/ui/react-select";
import { Checkbox } from "@/components/ui/checkbox";
import type { Role } from "@/api/permissions/types";
import { toast } from "sonner";

interface StagePermissionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  roles: Role[];
  editingPermission?: {
    id: string;
    roleId: string;
    canView: boolean;
    canEdit: boolean;
    canDelete: boolean;
  };
  onSave: (data: {
    roleId: string;
    canView: boolean;
    canEdit: boolean;
    canDelete: boolean;
  }) => void;
  isSaving: boolean;
  title: string;
  description: string;
}

export function StagePermissionDialog({
  open,
  onOpenChange,
  roles,
  editingPermission,
  onSave,
  isSaving,
  title,
  description,
}: StagePermissionDialogProps) {
  const [selectedRoleId, setSelectedRoleId] = React.useState<string>("");
  const [canView, setCanView] = React.useState<boolean>(true);
  const [canEdit, setCanEdit] = React.useState<boolean>(false);
  const [canDelete, setCanDelete] = React.useState<boolean>(false);

  // Reset form when dialog opens or editing permission changes
  React.useEffect(() => {
    if (open) {
      if (editingPermission) {
        setSelectedRoleId(editingPermission.roleId);
        setCanView(editingPermission.canView);
        setCanEdit(editingPermission.canEdit);
        setCanDelete(editingPermission.canDelete);
      } else {
        setSelectedRoleId("");
        setCanView(true);
        setCanEdit(false);
        setCanDelete(false);
      }
    }
  }, [open, editingPermission]);

  const handleSave = () => {
    if (!selectedRoleId) {
      toast.error("Please select a role");
      return;
    }

    onSave({
      roleId: selectedRoleId,
      canView,
      canEdit,
      canDelete,
    });
  };

  const availableRoles = roles;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="role" className="text-sm font-medium">
              Role
            </Label>
            <ReactSelect
              id="role"
              value={selectedRoleId}
              onValueChange={setSelectedRoleId}
              disabled={!!editingPermission}
              allowEmpty
              emptyOptionLabel="Select a role"
              placeholder="Select a role"
              options={availableRoles
                .filter((role) => role.id)
                .map((role) => ({
                  value: role.id!,
                  label: role.name,
                }))}
              aria-label="Role"
            />
          </div>

          <div className="grid gap-4">
            <Label className="text-sm font-medium">Permissions</Label>
            <div className="space-y-3">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="canView"
                  checked={canView}
                  onCheckedChange={(checked) => setCanView(checked as boolean)}
                />
                <Label htmlFor="canView" className="text-sm font-normal">
                  Can view stage name
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="canEdit"
                  checked={canEdit}
                  onCheckedChange={(checked) => setCanEdit(checked as boolean)}
                />
                <Label htmlFor="canEdit" className="text-sm font-normal">
                  Can edit stage name
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="canDelete"
                  checked={canDelete}
                  onCheckedChange={(checked) => setCanDelete(checked as boolean)}
                />
                <Label htmlFor="canDelete" className="text-sm font-normal">
                  Can delete stage name
                </Label>
              </div>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSaving}
          >
            Cancel
          </Button>
          <Button
            type="button"
            onClick={handleSave}
            disabled={isSaving || !selectedRoleId}
          >
            {isSaving ? "Saving..." : editingPermission ? "Update" : "Create"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
