import { useState } 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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Form,
  FormControl,
  FormDescription,
  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 { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';

import { Loader2, Trash } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { submitTimelineEvent, submitTimelineEventUpdate, deleteTimelineEvent } from '@/lib/entitySubmissionHelpers';
import { handleError } from '@/lib/errorHandler';
import type {
  EntityType,
  TimelineEventFormData,
} from '@/types/timeline';

// Validation schema
const timelineEventSchema = z.object({
  event_type: z.enum([
    'name_change',
    'operator_change',
    'owner_change',
    'location_change',
    'status_change',
    'opening',
    'closure',
    'reopening',
    'renovation',
    'expansion',
    'acquisition',
    'milestone',
    'other',
  ]),
  event_date: z.date({
    message: 'Event date is required',
  }),
  event_date_precision: z.enum(['day', 'month', 'year']).default('day'),
  title: z.string().min(1, 'Title is required').max(200, 'Title is too long'),
  description: z.string().max(1000, 'Description is too long').optional(),
  
  // Conditional fields
  from_value: z.string().max(200).optional(),
  to_value: z.string().max(200).optional(),
  from_entity_id: z.string().uuid().optional(),
  to_entity_id: z.string().uuid().optional(),
  from_location_id: z.string().uuid().optional(),
  to_location_id: z.string().uuid().optional(),
  
  is_public: z.boolean().default(true),
});

interface TimelineEventEditorDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  entityType: EntityType;
  entityId: string;
  entityName: string;
  existingEvent?: any;
  onSuccess?: () => void;
}

export function TimelineEventEditorDialog({
  open,
  onOpenChange,
  entityType,
  entityId,
  entityName,
  existingEvent,
  onSuccess,
}: TimelineEventEditorDialogProps) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  
  const isEditing = !!existingEvent;
  const dialogTitle = isEditing ? 'Edit Timeline Event' : 'Add Timeline Event';
  const submitButtonText = isEditing ? 'Update Event' : 'Submit for Review';

  const form = useForm<TimelineEventFormData>({
    resolver: zodResolver(timelineEventSchema),
    defaultValues: existingEvent ? {
      event_type: existingEvent.event_type,
      event_date: new Date(existingEvent.event_date),
      event_date_precision: existingEvent.event_date_precision,
      title: existingEvent.title,
      description: existingEvent.description || '',
      from_value: existingEvent.from_value || '',
      to_value: existingEvent.to_value || '',
      from_entity_id: existingEvent.from_entity_id || '',
      to_entity_id: existingEvent.to_entity_id || '',
      from_location_id: existingEvent.from_location_id || '',
      to_location_id: existingEvent.to_location_id || '',
    } : {
      event_type: 'milestone',
      event_date: new Date(),
      event_date_precision: 'day',
      title: '',
      description: '',
    },
  });

  const selectedEventType = form.watch('event_type');

  const onSubmit = async (data: TimelineEventFormData) => {
    if (!user) {
      toast({
        title: 'Authentication required',
        description: 'You must be logged in to submit timeline events.',
        variant: 'destructive',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      if (isEditing) {
        await submitTimelineEventUpdate(existingEvent.id, data, user.id);
        toast({
          title: 'Timeline event update submitted',
          description: 'Your update has been submitted for moderator review.',
        });
      } else {
        await submitTimelineEvent(entityType, entityId, data, user.id);
        toast({
          title: 'Timeline event submitted',
          description: 'Your timeline event has been submitted for moderator review.',
        });
      }
      
      form.reset();
      onOpenChange(false);
      onSuccess?.();
    } catch (error: unknown) {
      handleError(error, {
        action: isEditing ? 'Update Timeline Event' : 'Submit Timeline Event',
        userId: user?.id,
        metadata: { entityType, entityId }
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!existingEvent || !user) return;
    
    setIsDeleting(true);
    try {
      await deleteTimelineEvent(existingEvent.id, user.id);
      toast({
        title: 'Event deleted',
        description: 'Your timeline event has been deleted successfully.',
      });
      onSuccess?.();
      onOpenChange(false);
      setShowDeleteConfirm(false);
      form.reset();
    } catch (error: unknown) {
      handleError(error, {
        action: 'Delete Timeline Event',
        userId: user?.id,
        metadata: { eventId: existingEvent?.id }
      });
    } finally {
      setIsDeleting(false);
    }
  };

  // Event type configurations for conditional field rendering
  const showFromTo = [
    'name_change',
    'operator_change',
    'owner_change',
    'status_change',
  ].includes(selectedEventType);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {dialogTitle}
          </DialogTitle>
          <DialogDescription>
            Add a historical milestone or event for {entityName}. 
            All submissions go through moderator review.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <FormField
              control={form.control}
              name="event_type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Event Type</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    defaultValue={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Select event type" />
                      </SelectTrigger>
                    </FormControl>
                  <SelectContent>
                    <SelectItem value="name_change">Name Change</SelectItem>
                    <SelectItem value="operator_change">Operator Change</SelectItem>
                    <SelectItem value="owner_change">Ownership Change</SelectItem>
                    <SelectItem value="location_change">Relocation</SelectItem>
                    <SelectItem value="status_change">Status Change</SelectItem>
                    <SelectItem value="opening">Opening</SelectItem>
                    <SelectItem value="closure">Closure</SelectItem>
                    <SelectItem value="reopening">Reopening</SelectItem>
                    <SelectItem value="renovation">Renovation</SelectItem>
                    <SelectItem value="expansion">Expansion</SelectItem>
                    <SelectItem value="acquisition">Acquisition</SelectItem>
                    <SelectItem value="milestone">Milestone</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Event Title</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="e.g., Renamed to Six Flags"
                      {...field}
                    />
                  </FormControl>
                  <FormDescription>
                    A brief, descriptive title for this event
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="event_date"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>Event Date</FormLabel>
                    <DatePicker
                      date={field.value}
                      onSelect={field.onChange}
                      fromYear={1800}
                      toYear={new Date().getFullYear() + 10}
                    />
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="event_date_precision"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Date Precision</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="day">Exact Day</SelectItem>
                        <SelectItem value="month">Month Only</SelectItem>
                        <SelectItem value="year">Year Only</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {showFromTo && (
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="from_value"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>From</FormLabel>
                      <FormControl>
                        <Input placeholder="Previous value" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="to_value"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>To</FormLabel>
                      <FormControl>
                        <Input placeholder="New value" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            )}

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description (Optional)</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Additional context about this event..."
                      rows={4}
                      {...field}
                    />
                  </FormControl>
                  <FormDescription>
                    Provide additional details, context, or sources
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter className="gap-3 sm:gap-0">
              {isEditing && existingEvent?.approved_by === null && (
                <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
                  <AlertDialogTrigger asChild>
                    <Button
                      type="button"
                      variant="destructive"
                      disabled={isSubmitting}
                      className="sm:mr-auto"
                    >
                      <Trash className="w-4 h-4 mr-2" />
                      Delete Event
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Delete Timeline Event?</AlertDialogTitle>
                      <AlertDialogDescription>
                        This will permanently delete this timeline event. This action cannot be undone.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Cancel</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={handleDelete}
                        disabled={isDeleting}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        {isDeleting ? "Deleting..." : "Delete"}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {submitButtonText}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
