'use client';

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

import { FormField } from '@/components/form';
import { PermissionTree } from '@/components/permission-tree';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
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>;
  errors: FieldErrors<PlanFormValues>;
  isSubmitted: boolean;
  onSubmit: ComponentProps<'form'>['onSubmit'];
  canSubmit: boolean;
  permissionTree: PermissionTreeItem[];
  permissionIds: number[];
  onPermissionIdsChange: (ids: number[]) => void;
  isPermissionsLoading: boolean;
  isSaving: boolean;
}

export function PlanSheet({
  open,
  onOpenChange,
  planId,
  register,
  control,
  errors,
  isSubmitted,
  onSubmit,
  canSubmit,
  permissionTree,
  permissionIds,
  onPermissionIdsChange,
  isPermissionsLoading,
  isSaving,
}: PlanSheetProps) {
  const fieldError = (field: keyof PlanFormValues) =>
    isSubmitted ? errors[field]?.message : undefined;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full gap-0 p-0 sm:max-w-3xl">
        <SheetHeader className="shrink-0 border-b px-6 py-4 pr-12">
          <SheetTitle className="text-lg leading-none font-semibold tracking-tight">
            {planId ? 'Edit Plan' : 'Create Plan'}
          </SheetTitle>
          <SheetDescription className="text-sm">
            Configure subscription limits, billing, and permission access.
          </SheetDescription>
        </SheetHeader>

        <form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
          <div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                id="plan-name"
                label="Name"
                required
                error={fieldError('name')}
              >
                <Input
                  id="plan-name"
                  placeholder="Enter plan name"
                  aria-invalid={!!fieldError('name')}
                  {...register('name')}
                />
              </FormField>

              <FormField
                id="plan-slug"
                label="Slug"
                required
                error={fieldError('slug')}
              >
                <Input
                  id="plan-slug"
                  placeholder="starter"
                  aria-invalid={!!fieldError('slug')}
                  {...register('slug')}
                />
              </FormField>
            </div>

            <FormField
              id="plan-description"
              label="Description"
              required
              error={fieldError('description')}
            >
              <Textarea
                id="plan-description"
                placeholder="Basic plan for small teams"
                aria-invalid={!!fieldError('description')}
                {...register('description')}
                className="min-h-20"
              />
            </FormField>

            <div className="grid gap-4 md:grid-cols-3">
              <FormField
                id="plan-price"
                label="Price"
                required
                error={fieldError('price')}
              >
                <Input
                  id="plan-price"
                  type="number"
                  min="0"
                  step="0.01"
                  placeholder="29.99"
                  aria-invalid={!!fieldError('price')}
                  {...register('price')}
                />
              </FormField>

              <FormField
                label="Billing Cycle"
                required
                error={fieldError('billing_cycle')}
              >
                <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>
                  )}
                />
              </FormField>

              <FormField
                id="plan-trial-days"
                label="Trial Days"
                error={fieldError('trial_days')}
              >
                <Input
                  id="plan-trial-days"
                  type="number"
                  min="0"
                  aria-invalid={!!fieldError('trial_days')}
                  {...register('trial_days', { valueAsNumber: true })}
                />
              </FormField>
            </div>

            <div className="grid gap-4 md:grid-cols-4">
              <FormField
                id="max-projects"
                label="Projects"
                error={fieldError('max_projects')}
              >
                <Input
                  id="max-projects"
                  type="number"
                  min="0"
                  aria-invalid={!!fieldError('max_projects')}
                  {...register('max_projects', { valueAsNumber: true })}
                />
              </FormField>

              <FormField
                id="max-organizations"
                label="Organizations"
                error={fieldError('max_organizations')}
              >
                <Input
                  id="max-organizations"
                  type="number"
                  min="0"
                  aria-invalid={!!fieldError('max_organizations')}
                  {...register('max_organizations', { valueAsNumber: true })}
                />
              </FormField>

              <FormField
                id="max-users"
                label="Users"
                error={fieldError('max_users')}
              >
                <Input
                  id="max-users"
                  type="number"
                  min="0"
                  aria-invalid={!!fieldError('max_users')}
                  {...register('max_users', { valueAsNumber: true })}
                />
              </FormField>

              <FormField
                id="max-roles"
                label="Roles"
                error={fieldError('max_roles')}
              >
                <Input
                  id="max-roles"
                  type="number"
                  min="0"
                  aria-invalid={!!fieldError('max_roles')}
                  {...register('max_roles', { valueAsNumber: true })}
                />
              </FormField>
            </div>

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

            <FormField
              label="Permissions"
              required
              error={fieldError('permission_ids')}
              className="space-y-3"
              labelEnd={
                <span className="text-muted-foreground">
                  {permissionIds.length} selected
                </span>
              }
            >
              {isPermissionsLoading ? (
                <div className="rounded-lg border p-6 text-muted-foreground">
                  Loading permissions...
                </div>
              ) : (
                <PermissionTree
                  items={permissionTree}
                  selectedIds={permissionIds}
                  onChange={onPermissionIdsChange}
                />
              )}
            </FormField>
          </div>

          <SheetFooter className="shrink-0 border-t px-6 py-4 sm:flex-row sm:justify-end">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isSaving}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSaving || !canSubmit}>
              {isSaving ? (
                <Loader2 className="mr-2 size-4 animate-spin" />
              ) : null}
              {planId ? 'Update Plan' : 'Create Plan'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
