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

export type NoteFormValues = z.infer<typeof NoteFormSchema>;

export type NormalizedNotePayload = {
    title: string;
    description: string;
    tags?: string[];
    color?: string;
    date?: string;
    people?: string[];
    bullets?: string[];
};

interface UserOption {
    label: string;
    value: string;
}

interface StatusOption {
    label: string;
    value: string;
}

interface NoteTag {
    value: number;
    label: string;
    color: string;
}

interface NoteFormProps {
    mode: 'add' | 'edit';
    initialNote?: any;
    onSubmitNote: (payload: NormalizedNotePayload) => void;
    onCancel?: () => void;
    className?: string;
    users?: UserOption[];
    statuses?: StatusOption[];
    noteTags?: NoteTag[];
}

const NoteFormSchema = z.object({
    title: z.string().min(3, 'Title must be at least 3 characters'),
    tags: z.array(z.string()).optional(),
    content: z.string().max(1000).optional().or(z.literal('')),
    color: z.string().optional(),
    date: z.string().optional(),
    people: z.array(z.string()).optional(),
    bullets: z.array(z.string()).optional(),
});

export default function NoteForm({ mode, initialNote, onSubmitNote, onCancel, className, users = [], statuses = [], noteTags = [] }: NoteFormProps) {
    // Extract tag options for multiselect
    const tagOptions = noteTags.map((tag) => ({
        value: tag.label,
        label: tag.label,
    }));

    // Normalize initialNote to form field names
    const mappedInitial = initialNote
        ? {
              title: initialNote.title || '',
              content: initialNote.content || '',
              // Convert tag objects to tag names for the form
              tags: Array.isArray(initialNote.tags)
                  ? initialNote.tags.map((tag: any) => (typeof tag === 'string' ? tag : tag.name))
                  : initialNote.tag
                    ? [initialNote.tag]
                    : [], // Fallback for old single tag column
              // Convert people to array of strings (user IDs) for multiselect
              people: Array.isArray(initialNote.people) ? initialNote.people.map((p: any) => String(typeof p === 'object' ? p.id : p)) : [],
              date: initialNote.date || undefined,
          }
        : {};

    const defaultValues = {
        title: '',
        content: '',
        tags: [],
        date: undefined,
        people: [],
        ...mappedInitial,
    };

    const resolver = zodResolver(NoteFormSchema);

    const handleSubmit = async (values: NoteFormValues) => {
        const payload: NormalizedNotePayload = {
            title: values.title || '',
            description: values.content || '',
            tags: values.tags || [],
            color: values.color,
            date: values.date,
            people: values.people || [],
            bullets: values.bullets || [],
        };

        onSubmitNote(payload);
    };

    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: Sprint Planning Notes" required />

                <FormField name="content" label="Content" type="textarea" />

                <FormField
                    name="tags"
                    label="Tags"
                    type="multiselect"
                    options={
                        tagOptions.length > 0
                            ? tagOptions
                            : [
                                  { value: 'Work', label: 'Work' },
                                  { value: 'Personal', label: 'Personal' },
                                  { value: 'Important', label: 'Important' },
                              ]
                    }
                    placeholder="Select tags"
                    searchable={true}
                />

                <FormField name="date" label="Select Date" type="date" />

                {/* Select follower (single-select via searchable-multiselect) */}
                {users && users.length > 0 && (
                    <FormField
                        name="people"
                        label="Select Follower"
                        type="multiselect"
                        searchable
                        options={users}
                        placeholder="Select Follower"
                        max={10}
                        allowCustomOptions={false}
                        required={false}
                    />
                )}

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