import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
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 { useToast } from "@/hooks/use-toast";
import { supabase } from '@/integrations/supabase/client';
import { Loader2 } from "lucide-react";

const formSchema = z.object({
  email_address: z.string().email("Invalid email address format").min(5, "Email is too short"),
  association_id: z.string().min(1, "Please select an association"),
});

export default function EmailAddressDialog({ open, onOpenChange, onSuccess, preSelectedAssociationId = null }) {
  const [associations, setAssociations] = useState([]);
  const [loadingAssociations, setLoadingAssociations] = useState(false);
  const { toast } = useToast();

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email_address: '',
      association_id: preSelectedAssociationId || '',
    },
  });

  useEffect(() => {
    if (preSelectedAssociationId) {
      form.setValue('association_id', preSelectedAssociationId);
    }
  }, [preSelectedAssociationId, form]);

  useEffect(() => {
    if (open) {
      fetchAssociations();
      form.reset({
        email_address: '',
        association_id: preSelectedAssociationId || '',
      });
    }
  }, [open]);

  const fetchAssociations = async () => {
    setLoadingAssociations(true);
    try {
      const { data, error } = await supabase
        .from('associations')
        .select('id, name')
        .order('name');
      
      if (error) throw error;
      setAssociations(data || []);
    } catch (error) {
      console.error('Error fetching associations:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load associations list.",
      });
    } finally {
      setLoadingAssociations(false);
    }
  };

  const onSubmit = async (values) => {
    try {
      // Check if email already exists
      const { data: existing } = await supabase
        .from('client_email_addresses')
        .select('id')
        .eq('email_address', values.email_address)
        .maybeSingle();
      
      if (existing) {
        toast({
          variant: "destructive",
          title: "Duplicate Email",
          description: "This email address is already assigned to an association.",
        });
        return;
      }

      const { error } = await supabase
        .from('client_email_addresses')
        .insert({
          client_id: values.association_id,
          email_address: values.email_address,
        });

      if (error) throw error;

      toast({
        title: "Success",
        description: "Email routing rule created successfully.",
      });
      
      onSuccess?.();
      onOpenChange(false);
    } catch (error) {
      console.error('Error creating email rule:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message || "Failed to create email routing rule.",
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Add Email Routing Rule</DialogTitle>
          <DialogDescription>
            Assign an email address to an association. All emails sent to this address will be routed to the selected association.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="association_id"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Association</FormLabel>
                  <Select 
                    onValueChange={field.onChange} 
                    defaultValue={field.value}
                    value={field.value}
                  >
                    <FormControl>
                      <SelectTrigger disabled={loadingAssociations}>
                        <SelectValue placeholder={loadingAssociations ? "Loading..." : "Select an association"} />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {associations.map((assoc) => (
                        <SelectItem key={assoc.id} value={assoc.id}>
                          {assoc.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="email_address"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email Address</FormLabel>
                  <FormControl>
                    <Input placeholder="e.g. board@oceanview.example.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter className="pt-4">
              <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 Rule
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
