import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { supabase } from '@/integrations/supabase/client';
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import {
  Form, FormControl, FormField, FormItem, FormLabel, FormMessage,
} from "@/components/ui/form";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

const formSchema = z.object({
  description: z.string().min(1, "Description is required"),
  fee: z.coerce.number().min(0, "Fee must be 0 or greater"),
  category: z.string().min(1, "Category is required"),
  subcategory: z.string().min(1, "Subcategory is required"),
  account: z.string().optional(),
});


export function FeeScheduleDialog({ open, onOpenChange, onSuccess, item = null }) {
  const { toast } = useToast();
  const [subcategories, setSubcategories] = useState([]);
  const [categories, setCategories] = useState([]);

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      description: '',
      fee: '',
      category: '',
      subcategory: '',
      account: '',
    },
  });

  useEffect(() => {
    if (open) {
      fetchSubcategories();
      fetchCategories();
      if (item) {
        form.reset({
          description: item.description,
          fee: item.fee,
          category: item.category || '',
          subcategory: item.subcategory || '',
          account: item.account || '',
        });
      } else {
        form.reset({
          description: '',
          fee: '',
          category: '',
          subcategory: '',
          account: '',
        });
      }
    }
  }, [open, item, form]);

  const fetchSubcategories = async () => {
    const { data } = await supabase
      .from('expense_subcategories')
      .select('*')
      .eq('is_active', true)
      .order('name');
    setSubcategories(data || []);
  };

  const fetchCategories = async () => {
    const { data } = await supabase
      .from('expense_categories')
      .select('*')
      .eq('is_active', true)
      .order('name');
    setCategories(data || []);
  };

  const onSubmit = async (values) => {
    try {
      const payload = {
        description: values.description,
        fee: values.fee,
        category: values.category,
        subcategory: values.subcategory,
        account: values.account || null,
        updated_at: new Date().toISOString(),
      };

      let error;
      if (item) {
        const result = await supabase
          .from('fee_schedules')
          .update(payload)
          .eq('id', item.id);
        error = result.error;
      } else {
        const result = await supabase
          .from('fee_schedules')
          .insert([payload]);
        error = result.error;
      }

      if (error) throw error;

      toast({
        title: item ? "Updated" : "Created",
        description: `Fee schedule item has been ${item ? "updated" : "created"} successfully.`,
      });
      
      window.dispatchEvent(new Event('feeScheduleUpdated'));
      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('Error saving fee schedule:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message || "Failed to save fee schedule item.",
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{item ? "Edit Fee Item" : "Add Fee Item"}</DialogTitle>
          <DialogDescription>
            {item ? "Edit the details of this fee schedule item." : "Add a new item to the fee schedule."}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Service / Item Description <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input placeholder="e.g. Estoppel Fee" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Category <span className="text-destructive">*</span></FormLabel>
                    <Select onValueChange={field.onChange} value={field.value || ""}>
                      <FormControl>
                        <SelectTrigger><SelectValue placeholder="Select..." /></SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {categories.map((cat) => (
                          <SelectItem key={cat.id} value={cat.name}>{cat.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="subcategory"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Subcategory <span className="text-destructive">*</span></FormLabel>
                    <Select onValueChange={field.onChange} value={field.value || ""}>
                      <FormControl>
                        <SelectTrigger><SelectValue placeholder="Select..." /></SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {subcategories.map((sub) => (
                          <SelectItem key={sub.id} value={sub.name}>{sub.name}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="account"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Account</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value || ""}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder="Select account..." /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {categories.map((cat) => (
                        <SelectItem key={cat.id} value={cat.name}>{cat.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="fee"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Fee Amount ($) <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input type="number" step="0.01" placeholder="0.00" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
              <Button type="submit" disabled={form.formState.isSubmitting}>
                {form.formState.isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Save
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
