import Form from '@admin/components/form/Form';
import FormField from '@admin/components/form/FormField';
import TextEditor from '@admin/components/rich-text-editor';
import { Button } from '@admin/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import { ArrowLeft, Paperclip, Trash } from 'lucide-react';
import React, { useState } from 'react';

interface EmailSendFormProps {
    onBack: () => void;
    onSend?: (email: { to: string[]; cc: string[]; bcc: string[]; subject: string; body: string }) => void;
    mode?: 'screen' | 'sidebar';
}

const EmailSendForm = ({ onBack, onSend, mode = 'screen' }: EmailSendFormProps) => {
    const isSidebarMode = mode === 'sidebar';
    const [showCc, setShowCc] = useState(false);
    const [showBcc, setShowBcc] = useState(false);
    const [attachments, setAttachments] = useState<File[]>([]);

    // Default form values for the email
    const defaultValues = {
        from: 'tamzeed@taskco.com',
        to: '',
        cc: [],
        bcc: [],
        subject: '',
        body: `<p>Hey mate! 👋</p>
<p>Exciting news! The Design Competition is now OPEN and we've got some updates to make it even more engaging:</p>
<p>To submit your masterpiece:</p>
<ul>
    <li>🚀 To submit your masterpiece, hop over to our submission page at <a href="http://www.designcompetitionawards.com/submitwork">www.designcompetitionawards.com/submitwork</a>.</li>
    <li>👤 Complete the submission form with all the details that make your work shine. Don't hold back on the magic!</li>
    <li>😊 Spread the word like confetti! Share this exciting opportunity with your creative buddies and let's make waves together.</li>
    <li>📝 Hurry, submissions close on July 20th!</li>
</ul>
<p>Remember, this isn't just a competition; it's a celebration of creativity, passion, and innovation. Let's turn your visions into masterpieces that inspire and captivate. Stay inspired, stay creative, and let's make this competition one for the ages!</p>`,
    };

    const handleSubmit = (data: any) => {
        if (onSend) {
            // Process recipient data based on its format
            const processRecipients = (recipients: any) => {
                if (!recipients) return [];

                // If it's an array of objects from searchable-multiselect
                if (Array.isArray(recipients) && recipients.length > 0 && typeof recipients[0] === 'object') {
                    return recipients.map((recipient) => recipient.value);
                }

                // If it's a string (from regular text input)
                if (typeof recipients === 'string') {
                    return recipients.split(',').map((email: string) => email.trim());
                }

                return Array.isArray(recipients) ? recipients : [];
            };

            onSend({
                to: data.to.split(',').map((email: string) => email.trim()),
                cc: processRecipients(data.cc),
                bcc: processRecipients(data.bcc),
                subject: data.subject,
                body: data.body,
            });
        }
        onBack();
    };

    const handleAttachmentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
            setAttachments([...attachments, ...Array.from(e.target.files)]);
        }
    };

    const removeAttachment = (index: number) => {
        setAttachments(attachments.filter((_, i) => i !== index));
    };
    const sampleMails = ['anis@example.com', 'john@example.com', 'sarah@example.com', 'tamzeed@taskco.com', 'anil@example.com'];
    return (
        <div className="flex h-full flex-col">
            {/* Email Compose Header */}
            {!isSidebarMode && (
                <div className="flex items-center justify-between border-b border-gray-200 p-2">
                    <div className="flex items-center space-x-2">
                        <Button variant="ghost" size="icon" onClick={onBack} className="h-8 w-8">
                            <ArrowLeft className="h-4 w-4" />
                        </Button>
                        <h2 className="font-medium">New Message</h2>
                    </div>
                </div>
            )}

            {/* Email Form with Form, FormField, and TextEditor */}
            <div className="flex-1 overflow-auto p-2">
                <Form submitHandler={handleSubmit} defaultValues={defaultValues} formClassNames="space-y-4">
                    {/* From field */}
                    <div className="flex items-center">
                        <label className="w-16 text-sm font-medium text-gray-700">From:</label>
                        <div className="flex-1 border-b">
                            <Select name="from" defaultValue={defaultValues.from}>
                                <SelectTrigger className="border-0 px-0 py-1 shadow-none">
                                    <SelectValue placeholder="Select email" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="tamzeed@taskco.com">tamzeed@taskco.com</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    {/* To field */}
                    <div className="flex items-center">
                        <label className="w-16 text-sm font-medium text-gray-700">To:</label>
                        <div className="flex-1">
                            <FormField
                                type="multiselect"
                                searchable
                                searchPlaceholder="Add email address"
                                options={sampleMails}
                                allowCustomOptions={true}
                                onCreate={(value: string) => ({ label: value, value })}
                                name="to"
                                placeholder="mail"
                                className="rounded-none border-0 border-b bg-white px-0 py-1 text-gray-500 shadow-none focus-visible:ring-0"
                            />
                        </div>
                        <Button
                            variant="ghost"
                            size="sm"
                            type="button"
                            className="text-xs text-gray-500"
                            onClick={() => {
                                setShowCc(!showCc);
                                setShowBcc(showCc ? showBcc : false);
                            }}
                        >
                            {showCc ? 'Hide' : 'Cc'}/{showBcc ? 'Hide' : 'Bcc'}
                        </Button>
                    </div>

                    {/* CC field */}
                    {showCc && (
                        <div className="flex items-center">
                            <label className="w-16 text-sm font-medium text-gray-700">Cc:</label>
                            <div className="flex-1">
                                <FormField
                                    type="multiselect"
                                    searchable
                                    name="cc"
                                    placeholder="cc"
                                    searchPlaceholder="Add email address"
                                    options={sampleMails}
                                    allowCustomOptions={true}
                                    className="border-0 px-0 py-1 text-gray-500 shadow-none focus-visible:ring-0"
                                    onCreate={(value: string) => ({ label: value, value })}
                                />
                            </div>
                        </div>
                    )}

                    {/* BCC field */}
                    {showBcc && (
                        <div className="flex items-center">
                            <label className="w-16 text-sm font-medium text-gray-700">Bcc:</label>
                            <div className="flex-1">
                                <FormField
                                    type="multiselect"
                                    searchable
                                    name="bcc"
                                    placeholder="Blind carbon copy recipients"
                                    searchPlaceholder="Add email address"
                                    options={sampleMails}
                                    allowCustomOptions={true}
                                    className="border-0 px-0 py-1 text-gray-500 shadow-none focus-visible:ring-0"
                                    onCreate={(value: string) => ({ label: value, value })}
                                />
                            </div>
                        </div>
                    )}

                    {/* Subject field */}
                    <div className="flex items-center pb-2">
                        <label className="w-16 text-sm font-medium text-gray-700">Subject:</label>
                        <div className="flex-1 border-b">
                            <FormField
                                type="text"
                                name="subject"
                                placeholder="Add a subject"
                                className="border-0 px-0 py-1 shadow-none focus-visible:ring-0"
                            />
                        </div>
                    </div>

                    {/* Email Body using Rich Text Editor */}
                    <div className="mt-2">
                        <TextEditor name="body" />
                    </div>

                    {/* Attachments */}
                    {attachments.length > 0 && (
                        <div className="space-y-2">
                            <h3 className="text-sm font-medium text-gray-700">Attachments</h3>
                            <div className="space-y-2">
                                {attachments.map((file, index) => (
                                    <div key={index} className="flex items-center justify-between rounded-md border border-gray-200 p-2">
                                        <div className="flex items-center">
                                            <Paperclip className="mr-2 h-4 w-4 text-gray-500" />
                                            <span className="text-sm">{file.name}</span>
                                        </div>
                                        <Button variant="ghost" size="icon" onClick={() => removeAttachment(index)}>
                                            <Trash className="h-4 w-4 text-gray-500" />
                                        </Button>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Hidden file upload input */}
                    <input id="file-upload" type="file" multiple className="hidden" onChange={handleAttachmentChange} />

                    {/* Form Actions */}
                    <div className={`mt-10 border-t border-gray-200 pt-3 2xl:mt-4 ${isSidebarMode && 'pt-16'}`}>
                        <div className="flex items-center gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                type="button"
                                className="flex items-center"
                                onClick={() => document.getElementById('file-upload')?.click()}
                            >
                                <Paperclip className="mr-2 h-4 w-4" />
                                Attach
                            </Button>
                            <Button variant="outline" size="sm" type="button">
                                Save Draft
                            </Button>
                            <div className="ml-auto">
                                <Button variant="default" size="sm" type="submit" className="px-6">
                                    Send
                                </Button>
                            </div>
                        </div>
                    </div>
                </Form>
            </div>
        </div>
    );
};

export default EmailSendForm;
