'use client';

import * as React from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
  createDocumentSequenceMutation,
  deleteDocumentSequenceMutation,
  resetDocumentSequenceMutation,
  updateDocumentSequenceMutation
} from '../mutations';
import { documentSequencesQueryOptions } from '../queries';
import type { DocumentSequenceListItem, DocumentSequenceMutationPayload } from '../types';

type SequenceState = {
  documentType: string;
  prefix: string;
  period: string;
  branchId: string;
  currentNumber: string;
  paddingLength: string;
  isActive: boolean;
};

function toState(sequence?: DocumentSequenceListItem): SequenceState {
  return {
    documentType: sequence?.documentType ?? 'quotation',
    prefix: sequence?.prefix ?? 'QT',
    period: sequence?.period ?? '',
    branchId: sequence?.branchId ?? '',
    currentNumber: String(sequence?.currentNumber ?? 0),
    paddingLength: String(sequence?.paddingLength ?? 3),
    isActive: sequence?.isActive ?? true
  };
}

function buildPayload(state: SequenceState): DocumentSequenceMutationPayload {
  return {
    documentType: state.documentType,
    prefix: state.prefix,
    period: state.period,
    branchId: state.branchId || null,
    currentNumber: Number(state.currentNumber || 0),
    paddingLength: Number(state.paddingLength || 3),
    isActive: state.isActive
  };
}

function SequenceDialog({
  open,
  onOpenChange,
  sequence
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  sequence?: DocumentSequenceListItem;
}) {
  const [state, setState] = React.useState<SequenceState>(toState(sequence));
  const createMutation = useMutation({
    ...createDocumentSequenceMutation,
    onSuccess: () => {
      toast.success('Sequence created');
      onOpenChange(false);
    },
    onError: (error) => toast.error(error instanceof Error ? error.message : 'Create failed')
  });
  const updateMutation = useMutation({
    ...updateDocumentSequenceMutation,
    onSuccess: () => {
      toast.success('Sequence updated');
      onOpenChange(false);
    },
    onError: (error) => toast.error(error instanceof Error ? error.message : 'Update failed')
  });

  React.useEffect(() => {
    if (open) {
      setState(toState(sequence));
    }
  }, [open, sequence]);

  async function onSubmit(event: React.FormEvent) {
    event.preventDefault();
    const payload = buildPayload(state);

    if (sequence) {
      await updateMutation.mutateAsync({ id: sequence.id, values: payload });
      return;
    }

    await createMutation.mutateAsync(payload);
  }

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{sequence ? 'Edit Sequence' : 'Create Sequence'}</DialogTitle>
          <DialogDescription>Preview never increments the counter. Generation remains server-side only.</DialogDescription>
        </DialogHeader>
        <form onSubmit={onSubmit} className='grid gap-4'>
          <Input placeholder='Document type' value={state.documentType} onChange={(e) => setState((current) => ({ ...current, documentType: e.target.value }))} />
          <div className='grid gap-4 md:grid-cols-2'>
            <Input placeholder='Prefix' value={state.prefix} onChange={(e) => setState((current) => ({ ...current, prefix: e.target.value }))} />
            <Input placeholder='Period' value={state.period} onChange={(e) => setState((current) => ({ ...current, period: e.target.value }))} />
          </div>
          <div className='grid gap-4 md:grid-cols-3'>
            <Input placeholder='Branch ID (optional)' value={state.branchId} onChange={(e) => setState((current) => ({ ...current, branchId: e.target.value }))} />
            <Input placeholder='Current number' value={state.currentNumber} onChange={(e) => setState((current) => ({ ...current, currentNumber: e.target.value }))} />
            <Input placeholder='Padding length' value={state.paddingLength} onChange={(e) => setState((current) => ({ ...current, paddingLength: e.target.value }))} />
          </div>
          <div className='flex items-center justify-between rounded-lg border px-4 py-3'>
            <div>
              <div className='font-medium'>Active</div>
              <div className='text-muted-foreground text-sm'>Inactive sequences can stay preserved for legacy numbering.</div>
            </div>
            <Switch checked={state.isActive} onCheckedChange={(checked) => setState((current) => ({ ...current, isActive: checked }))} />
          </div>
          <DialogFooter>
            <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type='submit' isLoading={isPending}>
              {sequence ? 'Save Sequence' : 'Create Sequence'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export function DocumentSequenceSettings() {
  const { data } = useSuspenseQuery(documentSequencesQueryOptions());
  const [dialogState, setDialogState] = React.useState<{ open: boolean; sequence?: DocumentSequenceListItem }>({
    open: false
  });
  const resetMutation = useMutation({
    ...resetDocumentSequenceMutation,
    onSuccess: () => toast.success('Sequence reset'),
    onError: (error) => toast.error(error instanceof Error ? error.message : 'Reset failed')
  });
  const deleteMutation = useMutation({
    ...deleteDocumentSequenceMutation,
    onSuccess: () => toast.success('Sequence deleted'),
    onError: (error) => toast.error(error instanceof Error ? error.message : 'Delete failed')
  });

  return (
    <div className='space-y-6'>
      <div className='flex items-center justify-between gap-4 rounded-lg border p-4'>
        <div>
          <div className='font-medium'>Document Sequence Admin</div>
          <div className='text-muted-foreground text-sm'>Maintain organization-scoped numbering strategy without rewriting historic document codes.</div>
        </div>
        <Button onClick={() => setDialogState({ open: true })}>
          <Icons.add className='mr-2 h-4 w-4' />
          Create Sequence
        </Button>
      </div>

      {data.items.length === 0 ? (
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center text-sm'>
          No document sequences configured yet.
        </div>
      ) : (
        data.items.map((sequence) => (
          <div key={sequence.id} className='rounded-xl border p-5'>
            <div className='flex flex-wrap items-start justify-between gap-4'>
              <div>
                <div className='text-xl font-semibold'>{sequence.documentType}</div>
                <div className='text-muted-foreground text-sm'>
                  {sequence.prefix}{sequence.period} • branch {sequence.branchId || 'default'}
                </div>
              </div>
              <div className='flex gap-2'>
                <Badge variant={sequence.isActive ? 'secondary' : 'outline'}>
                  {sequence.isActive ? 'Active' : 'Inactive'}
                </Badge>
                <Badge variant='outline'>Next {sequence.nextPreview}</Badge>
              </div>
            </div>
            <div className='mt-4 grid gap-4 md:grid-cols-4'>
              <div className='rounded-lg bg-muted/40 p-4'>
                <div className='text-muted-foreground text-xs'>Current Number</div>
                <div className='mt-1 text-sm font-medium'>{sequence.currentNumber}</div>
              </div>
              <div className='rounded-lg bg-muted/40 p-4'>
                <div className='text-muted-foreground text-xs'>Padding Length</div>
                <div className='mt-1 text-sm font-medium'>{sequence.paddingLength}</div>
              </div>
              <div className='rounded-lg bg-muted/40 p-4'>
                <div className='text-muted-foreground text-xs'>Updated At</div>
                <div className='mt-1 text-sm font-medium'>{new Date(sequence.updatedAt).toLocaleString()}</div>
              </div>
              <div className='rounded-lg bg-muted/40 p-4'>
                <div className='text-muted-foreground text-xs'>Preview</div>
                <div className='mt-1 text-sm font-medium'>{sequence.nextPreview}</div>
              </div>
            </div>
            <div className='mt-4 flex flex-wrap gap-2'>
              <Button variant='outline' onClick={() => setDialogState({ open: true, sequence })}>
                Edit Sequence
              </Button>
              <Button
                variant='outline'
                onClick={() =>
                  resetMutation.mutate({
                    id: sequence.id,
                    values: { currentNumber: 0 }
                  })
                }
                isLoading={resetMutation.isPending}
              >
                Reset Counter
              </Button>
              <Button variant='outline' onClick={() => deleteMutation.mutate(sequence.id)} isLoading={deleteMutation.isPending}>
                Delete
              </Button>
            </div>
          </div>
        ))
      )}

      <SequenceDialog
        open={dialogState.open}
        onOpenChange={(open) => setDialogState((current) => ({ ...current, open }))}
        sequence={dialogState.sequence}
      />
    </div>
  );
}
