
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from '@/components/ui/dialog';
import { Loader2 } from 'lucide-react';

export default function ParentCategoryDialog({ open, onOpenChange, category, clientId, onSuccess }) {
  const { toast } = useToast();
  const { register, handleSubmit, reset, setValue, formState: { errors, isSubmitting } } = useForm({
    defaultValues: { category_name: '', description: '' }
  });

  useEffect(() => {
    if (open) {
      if (category) {
        setValue('category_name', category.category_name);
        setValue('description', category.description || '');
      } else {
        reset({ category_name: '', description: '' });
      }
    }
  }, [open, category, setValue, reset]);

  const onSubmit = async (data) => {
    if (!clientId) {
      toast({ variant: "destructive", title: "Error", description: "No association selected." });
      return;
    }

    try {
      if (category) {
        const { error } = await supabase
          .from('parent_chart_of_accounts')
          .update({ category_name: data.category_name, description: data.description, updated_at: new Date().toISOString() })
          .eq('id', category.id);
        if (error) throw error;
        toast({ title: "Category Updated", description: "Parent category updated successfully." });
      } else {
        const { error } = await supabase
          .from('parent_chart_of_accounts')
          .insert({ client_id: clientId, category_name: data.category_name, description: data.description });
        if (error) throw error;
        toast({ title: "Category Created", description: "New parent category created successfully." });
      }
      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('Error saving category:', error);
      toast({ variant: "destructive", title: "Error", description: error.message || "Failed to save category." });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{category ? 'Edit Parent Category' : 'New Parent Category'}</DialogTitle>
          <DialogDescription>{category ? 'Update the category details below.' : 'Create a new parent category to group accounts.'}</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="category_name">Category Name</Label>
            <Input id="category_name" placeholder="e.g. Operating Expenses" {...register('category_name', { required: 'Category name is required' })} />
            {errors.category_name && <span className="text-xs text-destructive">{errors.category_name.message}</span>}
          </div>
          <div className="grid gap-2">
            <Label htmlFor="description">Description (Optional)</Label>
            <Textarea id="description" placeholder="Brief description..." {...register('description')} />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isSubmitting ? 'Saving...' : (category ? 'Save Changes' : 'Create Category')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
