import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Loader2, AlertCircle } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import {
  Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle,
} from '@/components/ui/dialog';
import {
  Form, FormControl, FormField, FormItem, FormLabel, FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';

const formSchema = z.object({
  title: z.string().min(1, 'Title is required'),
  description: z.string().min(1, 'Description is required'),
  association_id: z.string().min(1, 'Association is required'),
  category: z.string().optional(),
  case_number: z.string().optional(),
  attorney: z.string().optional(),
  status: z.string().min(1, 'Status is required'),
});

export default function LegalMatterDialog({ open, onOpenChange, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [associations, setAssociations] = useState([]);
  const [loadingAssociations, setLoadingAssociations] = useState(false);
  const [error, setError] = useState(null);

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      title: '',
      description: '',
      association_id: '',
      category: '',
      case_number: '',
      attorney: '',
      status: 'open',
    },
  });

  useEffect(() => {
    if (open) {
      fetchAssociations();
      form.reset();
      setError(null);
    }
  }, [open, form]);

  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 (err) {
      console.error('Error fetching associations:', err);
      setError('Failed to load associations.');
    } finally {
      setLoadingAssociations(false);
    }
  };

  const onSubmit = async (values) => {
    try {
      const { error: submitError } = await supabase.from('legal_matters').insert({
        title: values.title,
        description: values.description,
        association_id: values.association_id,
        category: values.category || null,
        case_number: values.case_number || null,
        attorney: values.attorney || null,
        status: values.status,
        created_by: user?.id,
      });

      if (submitError) throw submitError;

      toast({ title: 'Success', description: 'Legal matter created successfully.' });
      onSuccess();
      onOpenChange(false);
    } catch (err) {
      console.error('Error creating legal matter:', err);
      setError('Failed to create legal matter. Please try again.');
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] h-[90vh] sm:h-[85vh] flex flex-col p-0 overflow-hidden">
        <div className="p-6 border-b shrink-0">
          <DialogHeader>
            <DialogTitle>Create Legal Case</DialogTitle>
            <DialogDescription>Record a new legal matter case.</DialogDescription>
          </DialogHeader>

          {error && (
            <Alert variant="destructive" className="mt-4">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Error</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
        </div>

        <ScrollArea className="flex-1 p-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" id="legal-matter-form">
              <FormField
                control={form.control}
                name="association_id"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Association <span className="text-destructive">*</span></FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger disabled={loadingAssociations}>
                          <SelectValue placeholder="Select 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="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Case Title <span className="text-destructive">*</span></FormLabel>
                    <FormControl>
                      <Input placeholder="e.g., Pending Litigation" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Category</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="Dispute">Dispute</SelectItem>
                          <SelectItem value="Compliance">Compliance</SelectItem>
                          <SelectItem value="Litigation">Litigation</SelectItem>
                          <SelectItem value="Collection">Collection</SelectItem>
                          <SelectItem value="Other">Other</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Status <span className="text-destructive">*</span></FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger><SelectValue placeholder="Select status" /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="open">Open</SelectItem>
                          <SelectItem value="in_progress">In Progress</SelectItem>
                          <SelectItem value="resolved">Resolved</SelectItem>
                          <SelectItem value="closed">Closed</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="case_number"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Case / Docket Number</FormLabel>
                      <FormControl>
                        <Input placeholder="12-3456-CA" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="attorney"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Attorney</FormLabel>
                      <FormControl>
                        <Input placeholder="Attorney name or firm" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Matter Details <span className="text-destructive">*</span></FormLabel>
                    <FormControl>
                      <Textarea placeholder="Detailed description..." className="min-h-[120px]" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </ScrollArea>

        <div className="p-4 border-t bg-muted/30 flex justify-end shrink-0 gap-2">
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button type="submit" form="legal-matter-form" disabled={form.formState.isSubmitting}>
            {form.formState.isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Save Legal Case
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
