'use client';

import type { ComponentProps } from 'react';
import type { Control, UseFormRegister } from 'react-hook-form';
import { Controller } from 'react-hook-form';
import { Loader2 } from 'lucide-react';

import { PermissionTree } from '@/components/permission-tree';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import type { PermissionTreeItem } from '@/types';

import type { PlanFormValues } from '../hooks/usePlanForm';

interface PlanSheetProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  planId?: number;
  register: UseFormRegister<PlanFormValues>;
  control: Control<PlanFormValues>;
  onSubmit: ComponentProps<'form'>['onSubmit'];
  permissionTree: PermissionTreeItem[];
  permissionIds: number[];
  onPermissionIdsChange: (ids: number[]) => void;
  isPermissionsLoading: boolean;
  isSaving: boolean;
}

export function PlanSheet({
  open,
  onOpenChange,
  planId,
  register,
  control,
  onSubmit,
  permissionTree,
  permissionIds,
  onPermissionIdsChange,
  isPermissionsLoading,
  isSaving,
}: PlanSheetProps) {
  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full overflow-y-auto sm:max-w-3xl">
        <SheetHeader>
          <SheetTitle>{planId ? 'Edit Plan' : 'Create Plan'}</SheetTitle>
          <SheetDescription>
            Configure subscription limits, billing, and permission access.
          </SheetDescription>
        </SheetHeader>
        <form onSubmit={onSubmit} className="flex flex-1 flex-col gap-5 px-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="plan-name">Name</Label>
              <Input
                id="plan-name"
                placeholder="Starter"
                {...register('name', { required: true })}
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="plan-slug">Slug</Label>
              <Input
                id="plan-slug"
                placeholder="starter"
                {...register('slug', { required: true })}
                required
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="plan-description">Description</Label>
            <textarea
              id="plan-description"
              placeholder="Basic plan for small teams"
              {...register('description', { required: true })}
              required
              className="min-h-20 w-full rounded-md border border-input bg-background px-3 py-2 outline-none focus-visible:border-ring"
            />
          </div>

          <div className="grid gap-4 md:grid-cols-3">
            <div className="space-y-2">
              <Label htmlFor="plan-price">Price</Label>
              <Input
                id="plan-price"
                type="number"
                min="0"
                step="0.01"
                placeholder="29.99"
                {...register('price', { required: true })}
                required
              />
            </div>
            <div className="space-y-2">
              <Label>Billing Cycle</Label>
              <Controller
                control={control}
                name="billing_cycle"
                render={({ field }) => (
                  <Select value={field.value} onValueChange={field.onChange}>
                    <SelectTrigger>
                      <SelectValue placeholder="Billing cycle" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="monthly">Monthly</SelectItem>
                      <SelectItem value="quarterly">Quarterly</SelectItem>
                      <SelectItem value="yearly">Yearly</SelectItem>
                    </SelectContent>
                  </Select>
                )}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="plan-trial-days">Trial Days</Label>
              <Input
                id="plan-trial-days"
                type="number"
                min="0"
                {...register('trial_days', { valueAsNumber: true })}
              />
            </div>
          </div>

          <div className="grid gap-4 md:grid-cols-4">
            <div className="space-y-2">
              <Label htmlFor="max-projects">Projects</Label>
              <Input
                id="max-projects"
                type="number"
                min="0"
                {...register('max_projects', { valueAsNumber: true })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="max-organizations">Organizations</Label>
              <Input
                id="max-organizations"
                type="number"
                min="0"
                {...register('max_organizations', { valueAsNumber: true })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="max-users">Users</Label>
              <Input
                id="max-users"
                type="number"
                min="0"
                {...register('max_users', { valueAsNumber: true })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="max-roles">Roles</Label>
              <Input
                id="max-roles"
                type="number"
                min="0"
                {...register('max_roles', { valueAsNumber: true })}
              />
            </div>
          </div>

          <div className="flex flex-wrap gap-5">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                className="size-4 rounded border-border accent-primary"
                {...register('is_active')}
              />
              Active
            </label>
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                className="size-4 rounded border-border accent-primary"
                {...register('is_custom')}
              />
              Custom plan
            </label>
          </div>

          <div className="space-y-3">
            <div className="flex items-center justify-between gap-3">
              <Label>Permissions</Label>
              <span className="text-muted-foreground">{permissionIds.length} selected</span>
            </div>
            {isPermissionsLoading ? (
              <div className="rounded-md border p-6 text-muted-foreground">
                Loading permissions...
              </div>
            ) : (
              <PermissionTree
                items={permissionTree}
                selectedIds={permissionIds}
                onChange={onPermissionIdsChange}
              />
            )}
          </div>

          <SheetFooter className="px-0">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isSaving}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSaving}>
              {isSaving ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
              {planId ? 'Update Plan' : 'Create Plan'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
