'use client';

import { useState } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle
} from '@/components/ui/sheet';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { permissionCatalogQueryOptions } from '../api/queries';
import {
  createPermissionTemplateMutation,
  updatePermissionTemplateMutation
} from '../api/mutations';
import type { PermissionTemplate } from '../api/types';
import {
  permissionTemplateSchema,
  type PermissionTemplateFormValues
} from '../schemas/permission-template';

interface PermissionTemplateFormSheetProps {
  template?: PermissionTemplate;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function PermissionTemplateFormSheet({
  template,
  open,
  onOpenChange
}: PermissionTemplateFormSheetProps) {
  const { data: catalog } = useSuspenseQuery(permissionCatalogQueryOptions());
  const isEdit = Boolean(template);

  const createMutation = useMutation({
    ...createPermissionTemplateMutation,
    onSuccess: () => {
      toast.success('สร้าง Permission Template เรียบร้อยแล้ว');
      onOpenChange(false);
      form.reset();
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถสร้าง Permission Template ได้');
    }
  });

  const updateMutation = useMutation({
    ...updatePermissionTemplateMutation,
    onSuccess: () => {
      toast.success('อัปเดต Permission Template เรียบร้อยแล้ว');
      onOpenChange(false);
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถอัปเดต Permission Template ได้');
    }
  });

  const form = useAppForm({
    defaultValues: {
      code: template?.code ?? '',
      name: template?.name ?? '',
      description: template?.description ?? '',
      is_default: template?.is_default ?? false,
      is_active: template?.is_active ?? true,
      permissions: template?.permissions ?? [],
      reason: ''
    } as PermissionTemplateFormValues,
    validators: {
      onSubmit: permissionTemplateSchema
    },
    onSubmit: async ({ value }) => {
      if (isEdit && template) {
        await updateMutation.mutateAsync({
          id: template.id,
          values: value
        });
        return;
      }

      await createMutation.mutateAsync(value);
    }
  });

  const { FormTextField, FormTextareaField, FormSwitchField } =
    useFormFields<PermissionTemplateFormValues>();
  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className='flex w-full flex-col sm:max-w-3xl'>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Permission Template' : 'New Permission Template'}</SheetTitle>
          <SheetDescription>
            จัดการชุดสิทธิ์ต้นแบบขององค์กร โดยยังไม่กระทบระบบ role เดิมระหว่างช่วง migration
          </SheetDescription>
        </SheetHeader>

        <div className='flex-1 overflow-auto'>
          <form.AppForm>
            <form.Form id='permission-template-form' className='space-y-6'>
              <div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
                <FormTextField
                  name='code'
                  label='Template Code'
                  required
                  placeholder='employee-template'
                />
                <FormTextField
                  name='name'
                  label='Template Name'
                  required
                  placeholder='Employee / User'
                />
              </div>

              <FormTextareaField
                name='description'
                label='Description'
                placeholder='อธิบายการใช้งานของ template นี้'
                rows={3}
              />

              <div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
                <FormSwitchField
                  name='is_default'
                  label='Default Template'
                  description='กำหนดเป็น template เริ่มต้นขององค์กร'
                />
                <FormSwitchField
                  name='is_active'
                  label='Active Template'
                  description='ปิดใช้งานเพื่อซ่อนจากการ assign รายใหม่'
                />
              </div>

              <FormTextareaField
                name='reason'
                label='Reason'
                placeholder='ระบุเหตุผลสำหรับการเปลี่ยนแปลงครั้งนี้'
                rows={2}
              />

              <form.AppField
                name='permissions'
                mode='array'
                children={(field) => {
                  const values = field.state.value ?? [];

                  return (
                    <field.FieldSet>
                      <field.FieldLabel>Permissions</field.FieldLabel>
                      <div className='space-y-4'>
                        {catalog.groups.map((group) => (
                          <div key={group.key} className='rounded-lg border p-4'>
                            <div className='mb-3 flex items-center justify-between gap-2'>
                              <div>
                                <h3 className='font-medium'>{group.label}</h3>
                                <p className='text-muted-foreground text-xs'>
                                  เลือกสิทธิ์ที่ต้องการใน module นี้
                                </p>
                              </div>
                              <Badge variant='outline'>{group.permissions.length} permissions</Badge>
                            </div>
                            <div className='grid grid-cols-1 gap-3 md:grid-cols-2'>
                              {group.permissions.map((permission) => {
                                const checked = values.includes(permission.value);

                                return (
                                  <div
                                    key={permission.value}
                                    className='flex items-start gap-3 rounded-md border p-3'
                                  >
                                    <Checkbox
                                      id={`permission-${permission.value}`}
                                      checked={checked}
                                      onCheckedChange={(nextChecked) => {
                                        if (nextChecked) {
                                          field.pushValue(permission.value);
                                          return;
                                        }

                                        const index = values.indexOf(permission.value);
                                        if (index > -1) {
                                          field.removeValue(index);
                                        }
                                      }}
                                    />
                                    <div className='space-y-1'>
                                      <Label htmlFor={`permission-${permission.value}`}>
                                        {permission.name}
                                      </Label>
                                      <p className='text-muted-foreground text-xs leading-5'>
                                        {permission.description}
                                      </p>
                                      <p className='text-muted-foreground font-mono text-[11px]'>
                                        {permission.code}
                                      </p>
                                    </div>
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        ))}
                      </div>
                      <field.FieldError />
                    </field.FieldSet>
                  );
                }}
              />
            </form.Form>
          </form.AppForm>
        </div>

        <SheetFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type='submit' form='permission-template-form' isLoading={isPending}>
            <Icons.check className='mr-2 h-4 w-4' />
            {isEdit ? 'Update Template' : 'Save Template'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}

export function PermissionTemplateFormSheetTrigger() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setOpen(true)}>
        <Icons.add className='mr-2 h-4 w-4' /> Add Template
      </Button>
      <PermissionTemplateFormSheet open={open} onOpenChange={setOpen} />
    </>
  );
}
