'use client';

import Form from '@/components/form/Form';
import FormField from '@/components/form/FormField';
import { Button } from '@/components/ui/button';
import { zodResolver } from '@hookform/resolvers/zod';
import { Plus } from 'lucide-react';
import { useFormContext } from 'react-hook-form';
import { z } from 'zod';

export type EventFormValues = z.infer<typeof EventFormSchema>;

export type NormalizedEventPayload = {
    name: string;
    description: string;
    type: 'project_kickoff' | 'progress_review' | 'emergency_review' | 'client_meeting' | 'internal_meeting' | 'presentation' | 'workshop' | 'other';
    date?: string;
    time?: string;
    location?: string;
    meeting_link?: string;
    duration?: number;
    participants?: string[];
};

interface EventFormProps {
    mode: 'add' | 'edit';
    initialEvent?: any;
    onSubmitEvent: (payload: NormalizedEventPayload) => void;
    onCancel?: () => void;
    className?: string;
}

const EventFormSchema = z.object({
    title: z.string().min(3, 'Title must be at least 3 characters'),
    type: z.enum(['project_kickoff', 'progress_review', 'emergency_review', 'client_meeting', 'internal_meeting', 'presentation', 'workshop', 'other']),
    description: z.string().max(1000).optional().or(z.literal('')),
    date: z.string().min(1, 'Date is required'),
    time: z.string().min(1, 'Time is required'),
    location: z.string().optional().or(z.literal('')),
    meeting_link: z.string().optional().or(z.literal('')),
    duration: z.union([z.number(), z.string()]).optional().transform(val => val ? Number(val) : 60),
    participants: z.array(z.string()).optional(),
});

export default function EventForm({ mode, initialEvent, onSubmitEvent, onCancel, className }: EventFormProps) {
    // Normalize initialEvent (event model) to form field names
    const mappedInitial = initialEvent
        ? {
              title: (initialEvent.title as string) || (initialEvent.name as string) || '',
              description: initialEvent.description || '',
              type: initialEvent.type || 'Meeting',
              date: initialEvent.date || '',
              time: initialEvent.time || '',
              location: initialEvent.location || '',
              attendees: initialEvent.attendees || [],
          }
        : {};

    const defaultValues = {
        title: '',
        description: '',
        type: 'client_meeting',
        date: '',
        time: '',
        location: '',
        meeting_link: '',
        duration: 60,
        participants: [],
        ...mappedInitial,
    };

    const resolver = zodResolver(EventFormSchema);

    const handleSubmit = async (values: EventFormValues) => {
        const name = values.title || '';
        const description = values.description || '';

        const payload: NormalizedEventPayload = {
            name,
            description,
            type: values.type,
            date: values.date,
            time: values.time,
            location: values.location,
            meeting_link: values.meeting_link,
            duration: values.duration || 60,
            participants: values.participants || [],
        };

        onSubmitEvent(payload);
    };

    const eventTypeOptions = [
        { value: 'project_kickoff', label: 'Project Kickoff' },
        { value: 'progress_review', label: 'Progress Review' },
        { value: 'emergency_review', label: 'Emergency Review' },
        { value: 'client_meeting', label: 'Client Meeting' },
        { value: 'internal_meeting', label: 'Internal Meeting' },
        { value: 'presentation', label: 'Presentation' },
        { value: 'workshop', label: 'Workshop' },
        { value: 'other', label: 'Other' },
    ];

    return (
        <div className={['space-y-6 p-2', className].filter(Boolean).join(' ')}>
            <Form submitHandler={handleSubmit} defaultValues={defaultValues} formClassNames="space-y-6" resolver={resolver}>
                <FormField name="title" label="Title" type="text" placeholder="eg: Project Kickoff Meeting" required />

                <FormField 
                    name="type" 
                    label="Event Type" 
                    type="select" 
                    options={eventTypeOptions}
                    required
                />

                {/* Date and Time side-by-side */}
                <div className="grid grid-cols-2 gap-4">
                    <FormField name="date" label="Date" type="date" required />
                    <FormField name="time" label="Time" type="time" required />
                </div>

                {/* Duration and Location */}
                <div className="grid grid-cols-2 gap-4">
                    <FormField 
                        name="duration" 
                        label="Duration (minutes)" 
                        type="number" 
                        placeholder="60"
                    />
                    <FormField 
                        name="location" 
                        label="Location" 
                        type="text" 
                        placeholder="Conference Room A" 
                    />
                </div>

                <FormField 
                    name="meeting_link" 
                    label="Meeting Link (optional)" 
                    type="text" 
                    placeholder="https://meet.google.com/..." 
                />

                {/* Participants */}
                <div>
                    <ParticipantSelector />
                </div>

                <FormField name="description" label="Description (optional)" type="textarea" />

                <div className="flex justify-end gap-3">
                    {onCancel && (
                        <Button variant="outline" onClick={onCancel} type="button">
                            Cancel
                        </Button>
                    )}
                    <Button className="hover:bg-success-800 bg-success text-white" type="submit">
                        <Plus className="h-4 w-4" />
                        {mode === 'add' ? 'Add Event' : 'Save Event'}
                    </Button>
                </div>
            </Form>
        </div>
    );
}

// Helper component to show participant selector
function ParticipantSelector() {
    const { watch } = useFormContext();

    // Sample options - ideally these would be passed via props or loaded from API
    const participantOptions = [
        { value: '1', label: 'Alice Johnson' },
        { value: '2', label: 'Bob Smith' },
        { value: '3', label: 'Charlie Brown' },
        { value: '4', label: 'David Wilson' },
        { value: '5', label: 'Emma Davis' },
    ];

    return (
        <FormField
            name="participants"
            label="Participants"
            type="multiselect"
            searchable
            options={participantOptions}
            placeholder="Select participants"
            max={20}
            allowCustomOptions={false}
        />
    );
}
