"use client";

import { useState, useEffect } from 'react';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/hooks/use-toast';
import { Loader2 } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

// Define the form schema
const soaFormSchema = z.object({
  ns1: z.string()
    .min(3, { message: 'Nameserver must be at least 3 characters' })
    .regex(/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, {
      message: 'Please enter a valid nameserver (e.g., ns1.example.com)',
    }),
  email: z.string()
    .email({ message: 'Please enter a valid email address' }),
});

interface Domain {
  domain: string;
  date_created: string;
  dnssec?: "enabled" | "disabled";
}

interface SOARecord {
  ns1?: string;
  email?: string;
}

interface DomainSettingsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  apiKey: string;
  domain: Domain;
  onDomainUpdated: (domain: Domain) => void;
}

export function DomainSettingsDialog({ 
  open, 
  onOpenChange, 
  apiKey, 
  domain, 
  onDomainUpdated 
}: DomainSettingsDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [dnssecEnabled, setDnssecEnabled] = useState(domain.dnssec === "enabled");
  const [soaRecord, setSOARecord] = useState<SOARecord | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const { toast } = useToast();

  const form = useForm<z.infer<typeof soaFormSchema>>({
    resolver: zodResolver(soaFormSchema),
    defaultValues: {
      ns1: '',
      email: '',
    },
  });

  // Fetch SOA record when dialog opens
  useEffect(() => {
    if (open) {
      fetchSOARecord();
    }
  }, [open, domain.domain, apiKey]);

  const fetchSOARecord = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/vultr/domains/${domain.domain}/soa`, {
        headers: {
          'X-API-Key': apiKey,
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch SOA record');
      }

      const data = await response.json();
      setSOARecord(data.soa);
      
      // Update form values
      form.setValue('ns1', data.soa.ns1 || '');
      form.setValue('email', data.soa.email || '');
    } catch (error) {
      console.error('Error fetching SOA record:', error);
      toast({
        title: 'Error',
        description: 'Failed to fetch SOA record',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const updateDNSSEC = async (enabled: boolean) => {
    try {
      setIsSubmitting(true);
      const response = await fetch(`/api/vultr/domains/${domain.domain}/dnssec`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey,
        },
        body: JSON.stringify({
          enabled,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to update DNSSEC settings');
      }

      setDnssecEnabled(enabled);
      onDomainUpdated({
        ...domain,
        dnssec: enabled ? "enabled" : "disabled",
      });

      toast({
        title: 'DNSSEC Updated',
        description: `DNSSEC has been ${enabled ? 'enabled' : 'disabled'} for ${domain.domain}`,
      });
    } catch (error) {
      console.error('Error updating DNSSEC:', error);
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to update DNSSEC settings',
        variant: 'destructive',
      });
      // Reset switch to previous state
      setDnssecEnabled(!enabled);
    } finally {
      setIsSubmitting(false);
    }
  };

  const onSubmitSOA = async (values: z.infer<typeof soaFormSchema>) => {
    try {
      setIsSubmitting(true);
      
      const response = await fetch(`/api/vultr/domains/${domain.domain}/soa`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': apiKey,
        },
        body: JSON.stringify({
          ns1: values.ns1,
          email: values.email,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to update SOA record');
      }

      toast({
        title: 'SOA Record Updated',
        description: `SOA record has been updated for ${domain.domain}`,
      });
      
      // Update local state
      setSOARecord({
        ns1: values.ns1,
        email: values.email,
      });
    } catch (error) {
      console.error('Error updating SOA record:', error);
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to update SOA record',
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Domain Settings: {domain.domain}</DialogTitle>
          <DialogDescription>
            Manage DNSSEC and SOA settings for your domain.
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue="dnssec" className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="dnssec">DNSSEC</TabsTrigger>
            <TabsTrigger value="soa">SOA Record</TabsTrigger>
          </TabsList>
          
          <TabsContent value="dnssec" className="py-4">
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <div className="font-medium">DNSSEC</div>
                  <p className="text-sm text-muted-foreground">
                    Enable DNSSEC to add an extra layer of security to your domain.
                  </p>
                </div>
                <Switch 
                  checked={dnssecEnabled}
                  disabled={isSubmitting}
                  onCheckedChange={updateDNSSEC}
                />
              </div>
              
              <div className="text-sm text-muted-foreground mt-4">
                <p>DNSSEC (Domain Name System Security Extensions) helps protect your domain from DNS spoofing attacks by digitally signing DNS data.</p>
                <p className="mt-2">Note: Enabling DNSSEC requires proper configuration with your domain registrar.</p>
              </div>
            </div>
          </TabsContent>
          
          <TabsContent value="soa" className="py-4">
            {isLoading ? (
              <div className="flex justify-center py-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : (
              <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmitSOA)} className="space-y-4">
                  <FormField
                    control={form.control}
                    name="ns1"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Primary Nameserver</FormLabel>
                        <FormControl>
                          <Input placeholder="ns1.example.com" {...field} />
                        </FormControl>
                        <FormDescription>
                          The primary nameserver for this domain
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="email"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Admin Email</FormLabel>
                        <FormControl>
                          <Input placeholder="admin@example.com" {...field} />
                        </FormControl>
                        <FormDescription>
                          The administrator email address for this domain
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <DialogFooter>
                    <Button type="submit" disabled={isSubmitting}>
                      {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                      Save Changes
                    </Button>
                  </DialogFooter>
                </form>
              </Form>
            )}
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
