"use client";

import React, { useEffect, useMemo } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useChatbotSettings, useUpdateChatbotSettings, ChatbotSetting } from '@/hooks/useChatbotSettings';
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { MultiSelectCombobox } from "@/components/ui/multi-select-combobox";
import { useInfiniteContacts } from '@/hooks/useWhatsApp';
import { useChatStore } from '@/store/useChatStore';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Smile, Bold, Italic, Strikethrough, Code } from "lucide-react";
import EmojiPicker from 'emoji-picker-react';

const FormattedTextarea = ({ value, onChange, placeholder, minHeight = "min-h-[100px]" }: { value: string, onChange: (val: string) => void, placeholder?: string, minHeight?: string }) => {
    const handleFormat = (format: string) => {
        let wrap = '';
        if (format === 'bold') wrap = '*';
        if (format === 'italic') wrap = '_';
        if (format === 'strikethrough') wrap = '~';
        if (format === 'monospace') wrap = '```';
        onChange(`${value || ''}${wrap}${wrap}`);
    };

    return (
        <div className="border border-gray-200 dark:border-gray-700 rounded-md overflow-hidden flex flex-col bg-white dark:bg-[#2a3942]">
            <Textarea 
                value={value}
                onChange={(e) => onChange(e.target.value)}
                placeholder={placeholder}
                className={`w-full border-0 focus-visible:ring-0 rounded-none resize-y ${minHeight} bg-transparent`}
            />
            <div className="flex items-center gap-1 p-1 bg-gray-50 dark:bg-[#202c33] border-t border-gray-200 dark:border-gray-700">
                <Popover>
                    <PopoverTrigger asChild>
                        <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0"><Smile className="w-4 h-4" /></Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0 border-none" align="start">
                        {/* @ts-ignore */}
                        <EmojiPicker onEmojiClick={(e) => onChange((value || '') + e.emoji)} />
                    </PopoverContent>
                </Popover>
                <div className="w-[1px] h-4 bg-gray-300 dark:bg-gray-600 mx-1"></div>
                <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0" onClick={() => handleFormat('bold')}><Bold className="w-4 h-4" /></Button>
                <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0" onClick={() => handleFormat('italic')}><Italic className="w-4 h-4" /></Button>
                <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0" onClick={() => handleFormat('strikethrough')}><Strikethrough className="w-4 h-4" /></Button>
                <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0" onClick={() => handleFormat('monospace')}><Code className="w-4 h-4" /></Button>
            </div>
        </div>
    );
};

const ChatbotSettingsView = () => {
    const { data: settings, isLoading } = useChatbotSettings();
    const { mutate: updateSettings, isPending } = useUpdateChatbotSettings();
    const { setSearchContact } = useChatStore();
    
    // Fetch contacts for the Combobox
    const { data: contactsData, isLoading: isLoadingContacts } = useInfiniteContacts();

    const [formData, setFormData] = React.useState<Partial<ChatbotSetting>>({
        is_active: false,
        chatbot_reset_days: 60,
        is_testing_mode: false,
        test_phone_numbers: '',
        is_out_of_office_active: false,
        is_out_of_office_testing_mode: false,
        out_of_office_test_phone_numbers: '',
        out_of_office_delay_minutes: 10,
        chatbot_greeting_message: '',
        chatbot_product_message: '',
        chatbot_location_message: '',
        chatbot_handoff_message: '',
        out_of_office_message: '',
        out_of_office_message_new_customer: '',
        out_of_office_cooldown_hours: 0,
        business_hours: {}
    });

    useEffect(() => {
        if (settings) {
            setFormData({
                is_active: settings.is_active,
                chatbot_reset_days: settings.chatbot_reset_days ?? 60,
                is_testing_mode: settings.is_testing_mode,
                test_phone_numbers: settings.test_phone_numbers || '',
                is_out_of_office_active: settings.is_out_of_office_active,
                is_out_of_office_testing_mode: settings.is_out_of_office_testing_mode,
                out_of_office_test_phone_numbers: settings.out_of_office_test_phone_numbers || '',
                out_of_office_delay_minutes: settings.out_of_office_delay_minutes ?? 10,
                chatbot_greeting_message: settings.chatbot_greeting_message || '',
                chatbot_product_message: settings.chatbot_product_message || '',
                chatbot_location_message: settings.chatbot_location_message || '',
                chatbot_handoff_message: settings.chatbot_handoff_message || '',
                out_of_office_message: settings.out_of_office_message || '',
                out_of_office_message_new_customer: settings.out_of_office_message_new_customer || '',
                out_of_office_cooldown_hours: settings.out_of_office_cooldown_hours ?? 0,
                business_hours: settings.business_hours || {}
            });
        }
    }, [settings]);

    const handleChange = (field: keyof ChatbotSetting, value: any) => {
        setFormData(prev => {
            const next = { ...prev, [field]: value };
            
            // Mutually exclusive toggle logic
            if (field === 'is_active' && value === true) {
                next.is_out_of_office_active = false;
            }
            if (field === 'is_out_of_office_active' && value === true) {
                next.is_active = false;
            }
            
            return next;
        });
    };

    const handleBusinessHourChange = (dayId: string, field: string, value: any) => {
        setFormData(prev => ({
            ...prev,
            business_hours: {
                ...prev.business_hours,
                [dayId]: {
                    ...(prev.business_hours?.[dayId] || { is_open: false, start: '08:00', end: '17:00' }),
                    [field]: value
                }
            }
        }));
    };

    const daysOfWeek = [
        { id: '1', name: 'Senin' },
        { id: '2', name: 'Selasa' },
        { id: '3', name: 'Rabu' },
        { id: '4', name: 'Kamis' },
        { id: '5', name: 'Jumat' },
        { id: '6', name: 'Sabtu' },
        { id: '7', name: 'Minggu' },
    ];

    const handleSave = () => {
        updateSettings(formData);
    };

    // Format contacts data for the Combobox
    const contactOptions = useMemo(() => {
        if (!contactsData?.pages) return [];
        return contactsData.pages.flatMap(page => 
            page.result.map(contact => ({
                value: contact.phone_number,
                label: `${contact.name} ${contact.last_name || ''} (${contact.phone_number})`,
                keywords: [contact.phone_number]
            }))
        );
    }, [contactsData]);

    if (isLoading) {
        return <div className="p-8 text-center text-gray-500">Loading settings...</div>;
    }

    return (
        <div className="flex-1 flex flex-col h-full bg-[#f0f2f5] dark:bg-[#111b21] overflow-y-auto relative">
            <div className="bg-white dark:bg-[#202c33] shadow-sm mb-6 px-6 py-4 flex items-center shrink-0 sticky top-0 z-10 justify-between">
                <h2 className="text-xl font-medium text-gray-900 dark:text-gray-100">Pengaturan Chatbot & Out of Office</h2>
                <Button onClick={handleSave} disabled={isPending} className="bg-teal-600 hover:bg-teal-700 text-white min-w-[150px]">
                    {isPending ? "Menyimpan..." : "Simpan Pengaturan"}
                </Button>
            </div>
            
            <div className="px-6 grid grid-cols-1 lg:grid-cols-2 gap-6 w-full max-w-[1400px] mx-auto pb-10">
                
                {/* 1. SECTION CHATBOT */}
                <div className={`bg-white dark:bg-[#202c33] p-6 rounded-lg shadow-sm border-t-4 border-teal-500 transition-opacity duration-300 ${!formData.is_active ? 'opacity-70' : ''}`}>
                    <div className="flex items-center justify-between mb-6 pb-4 border-b border-gray-100 dark:border-gray-800">
                        <div>
                            <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Mode Chatbot (24 Jam)</h3>
                            <p className="text-sm text-gray-500 mt-1">Jika aktif, chatbot berjalan 24 jam mengabaikan jam operasional.</p>
                        </div>
                        <Switch 
                            checked={formData.is_active} 
                            onCheckedChange={(c) => handleChange('is_active', c)} 
                        />
                    </div>
                    
                    <div className="space-y-6">
                        {/* Waktu Reset (Timeout) */}
                        <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-[#1a2328] rounded-lg border border-gray-100 dark:border-gray-800">
                            <div>
                                <h4 className="font-medium text-sm text-gray-900 dark:text-gray-100">Waktu Reset Chatbot</h4>
                                <p className="text-xs text-gray-500 mt-1">
                                    Chatbot akan mengirimkan pesan otomatis ke kontak yang sama lagi jika percakapan terakhir sudah melebihi batas waktu ini. (Jika kosong, default 60 hari)
                                </p>
                            </div>
                            <div className="flex items-center gap-2">
                                <Input 
                                    type="number"
                                    min="1"
                                    value={formData.chatbot_reset_days ?? ''}
                                    onChange={(e) => handleChange('chatbot_reset_days', parseInt(e.target.value) || 60)}
                                    className="w-20 text-center"
                                />
                                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Hari</span>
                            </div>
                        </div>

                        {/* Testing Mode Chatbot */}
                        <div className="p-4 bg-gray-50 dark:bg-[#1a2328] rounded-lg border border-gray-100 dark:border-gray-800">
                            <div className="flex items-center justify-between mb-4">
                                <div>
                                    <p className="font-medium text-sm text-gray-900 dark:text-gray-100">Mode Testing Chatbot</p>
                                    <p className="text-xs text-gray-500 mt-1">Hanya akan membalas ke nomor-nomor di bawah ini.</p>
                                </div>
                                <Switch 
                                    checked={formData.is_testing_mode} 
                                    onCheckedChange={(c) => handleChange('is_testing_mode', c)} 
                                />
                            </div>
                            <div className={`transition-all duration-300 overflow-hidden ${formData.is_testing_mode ? 'max-h-[300px] mt-4' : 'max-h-0'}`}>
                                <label className="block text-xs font-medium mb-2 text-gray-900 dark:text-gray-100">
                                    Nomor Telepon Testing
                                </label>
                                <div className="w-full relative">
                                    <MultiSelectCombobox 
                                        data={contactOptions}
                                        value={formData.test_phone_numbers ? formData.test_phone_numbers.split(',').filter(Boolean) : []}
                                        onChange={(val: string[]) => handleChange('test_phone_numbers', val.join(','))}
                                        onInputChange={(val: string) => setSearchContact(val)}
                                        placeholder="Cari dari daftar kontak..."
                                        loading={isLoadingContacts}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Alur Pesan Chatbot */}
                        <div>
                            <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-4 flex items-center">
                                <div className="w-6 h-6 rounded bg-teal-100 text-teal-700 flex items-center justify-center mr-2 text-xs font-bold">1</div>
                                Pesan Sapaan (Greeting)
                            </h4>
                            <FormattedTextarea 
                                value={formData.chatbot_greeting_message || ''}
                                onChange={(val) => handleChange('chatbot_greeting_message', val)}
                                minHeight="min-h-[80px]"
                            />
                        </div>
                        <div>
                            <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-4 flex items-center">
                                <div className="w-6 h-6 rounded bg-teal-100 text-teal-700 flex items-center justify-center mr-2 text-xs font-bold">2</div>
                                Opsi Produk
                            </h4>
                            <FormattedTextarea 
                                value={formData.chatbot_product_message || ''}
                                onChange={(val) => handleChange('chatbot_product_message', val)}
                                minHeight="min-h-[120px]"
                            />
                        </div>
                        <div>
                            <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-4 flex items-center">
                                <div className="w-6 h-6 rounded bg-teal-100 text-teal-700 flex items-center justify-center mr-2 text-xs font-bold">3</div>
                                Opsi Lokasi
                            </h4>
                            <FormattedTextarea 
                                value={formData.chatbot_location_message || ''}
                                onChange={(val) => handleChange('chatbot_location_message', val)}
                                minHeight="min-h-[100px]"
                            />
                        </div>
                        <div>
                            <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-4 flex items-center">
                                <div className="w-6 h-6 rounded bg-teal-100 text-teal-700 flex items-center justify-center mr-2 text-xs font-bold">4</div>
                                Pesan Handoff (Penutup)
                            </h4>
                            <FormattedTextarea 
                                value={formData.chatbot_handoff_message || ''}
                                onChange={(val) => handleChange('chatbot_handoff_message', val)}
                                minHeight="min-h-[80px]"
                            />
                        </div>
                    </div>
                </div>

                {/* 2. SECTION OUT OF OFFICE */}
                <div className={`bg-white dark:bg-[#202c33] p-6 rounded-lg shadow-sm border-t-4 border-amber-500 transition-opacity duration-300 ${!formData.is_out_of_office_active ? 'opacity-70' : ''}`}>
                    <div className="flex items-center justify-between mb-6 pb-4 border-b border-gray-100 dark:border-gray-800">
                        <div>
                            <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Mode Di Luar Jam Operasional</h3>
                            <p className="text-sm text-gray-500 mt-1">Sistem hanya membalas pesan secara otomatis di luar jam kerja.</p>
                        </div>
                        <Switch 
                            checked={formData.is_out_of_office_active} 
                            onCheckedChange={(c) => handleChange('is_out_of_office_active', c)} 
                        />
                    </div>

                    <div className="space-y-6">
                        {/* Waktu Delay OOO */}
                        <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-[#1a2328] rounded-lg border border-gray-100 dark:border-gray-800">
                            <div>
                                <h4 className="font-medium text-sm text-gray-900 dark:text-gray-100">Waktu Tunggu (Delay) Out-of-Office</h4>
                                <p className="text-xs text-gray-500 mt-1">
                                    Sistem akan menunda pengiriman pesan Out-of-Office selama batas waktu ini (agar admin ada kesempatan untuk membalas manual terlebih dahulu).
                                </p>
                            </div>
                            <div className="flex items-center gap-2">
                                <Input 
                                    type="number"
                                    min="1"
                                    value={formData.out_of_office_delay_minutes ?? ''}
                                    onChange={(e) => handleChange('out_of_office_delay_minutes', parseInt(e.target.value) || 10)}
                                    className="w-20 text-center"
                                />
                                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Menit</span>
                            </div>
                        </div>

                        {/* Cooldown OOO */}
                        <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-[#1a2328] rounded-lg border border-gray-100 dark:border-gray-800">
                            <div>
                                <h4 className="font-medium text-sm text-gray-900 dark:text-gray-100">Jeda Waktu (Cooldown) Pesan Out-of-Office</h4>
                                <p className="text-xs text-gray-500 mt-1">
                                    Sistem tidak akan mengirim pesan Out-of-Office lagi ke pelanggan yang sama dalam rentang waktu ini.
                                </p>
                            </div>
                            <div className="flex items-center gap-2">
                                <Input 
                                    type="number"
                                    min="0"
                                    value={formData.out_of_office_cooldown_hours ?? ''}
                                    onChange={(e) => handleChange('out_of_office_cooldown_hours', parseInt(e.target.value) || 0)}
                                    className="w-20 text-center"
                                />
                                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Jam</span>
                            </div>
                        </div>

                        {/* Testing Mode OOO */}
                        <div className="p-4 bg-gray-50 dark:bg-[#1a2328] rounded-lg border border-gray-100 dark:border-gray-800">
                            <div className="flex items-center justify-between mb-4">
                                <div>
                                    <p className="font-medium text-sm text-gray-900 dark:text-gray-100">Mode Testing Out-of-Office</p>
                                    <p className="text-xs text-gray-500 mt-1">Hanya akan membalas ke nomor-nomor di bawah ini.</p>
                                </div>
                                <Switch 
                                    checked={formData.is_out_of_office_testing_mode} 
                                    onCheckedChange={(c) => handleChange('is_out_of_office_testing_mode', c)} 
                                />
                            </div>
                            <div className={`transition-all duration-300 overflow-hidden ${formData.is_out_of_office_testing_mode ? 'max-h-[300px] mt-4' : 'max-h-0'}`}>
                                <label className="block text-xs font-medium mb-2 text-gray-900 dark:text-gray-100">
                                    Nomor Telepon Testing
                                </label>
                                <div className="w-full relative">
                                    <MultiSelectCombobox 
                                        data={contactOptions}
                                        value={formData.out_of_office_test_phone_numbers ? formData.out_of_office_test_phone_numbers.split(',').filter(Boolean) : []}
                                        onChange={(val: string[]) => handleChange('out_of_office_test_phone_numbers', val.join(','))}
                                        onInputChange={(val: string) => setSearchContact(val)}
                                        placeholder="Cari dari daftar kontak..."
                                        loading={isLoadingContacts}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* OOO Message */}
                        <div>
                            <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-gray-100">
                                Pesan Balasan Pelanggan Baru (Belum pernah chat sebelumnya)
                            </label>
                            <FormattedTextarea 
                                value={formData.out_of_office_message_new_customer || ''}
                                onChange={(val) => handleChange('out_of_office_message_new_customer', val)}
                                placeholder="Mohon maaf, saat ini kami sedang di luar jam operasional. Jam operasional kami adalah..."
                            />
                        </div>
                        <div className="mt-4">
                            <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-gray-100">
                                Pesan Balasan Pelanggan Lama (Sudah pernah chat sebelumnya)
                            </label>
                            <FormattedTextarea 
                                value={formData.out_of_office_message || ''}
                                onChange={(val) => handleChange('out_of_office_message', val)}
                                placeholder="Mohon maaf, saat ini kami sedang di luar jam operasional. Kami akan membalas pesan Anda segera..."
                            />
                        </div>

                        {/* Jam Operasional */}
                        <div className="mt-6">
                            <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-4">Konfigurasi Jam Operasional (Buka)</h4>
                            <div className="grid grid-cols-1 gap-3">
                                {daysOfWeek.map(day => {
                                    const config = formData.business_hours?.[day.id] || { is_open: false, start: '08:00', end: '17:00' };
                                    return (
                                        <div key={day.id} className="flex flex-col xl:flex-row items-start xl:items-center justify-between p-3 bg-gray-50 dark:bg-[#1a2328] rounded-md gap-4 border border-gray-100 dark:border-gray-800">
                                            <div className="flex items-center gap-3 min-w-[120px]">
                                                <Switch
                                                    checked={config.is_open}
                                                    onCheckedChange={(c) => handleBusinessHourChange(day.id, 'is_open', c)}
                                                />
                                                <span className="font-medium text-sm text-gray-900 dark:text-gray-100">{day.name}</span>
                                            </div>
                                            {config.is_open ? (
                                                <div className="flex items-center gap-2">
                                                    <Input
                                                        type="time"
                                                        value={config.start || '00:00'}
                                                        onChange={(e) => handleBusinessHourChange(day.id, 'start', e.target.value)}
                                                        className="bg-white dark:bg-[#202c33] border-gray-200 dark:border-gray-700 w-[130px] text-sm focus-visible:ring-amber-500"
                                                    />
                                                    <span className="text-gray-500 text-sm font-medium">s/d</span>
                                                    <Input
                                                        type="time"
                                                        value={config.end || '00:00'}
                                                        onChange={(e) => handleBusinessHourChange(day.id, 'end', e.target.value)}
                                                        className="bg-white dark:bg-[#202c33] border-gray-200 dark:border-gray-700 w-[130px] text-sm focus-visible:ring-amber-500"
                                                    />
                                                </div>
                                            ) : (
                                                <div className="text-sm text-gray-500 italic pr-4">Tutup (Libur)</div>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ChatbotSettingsView;
