import { ActivityLogSidebar } from '@admin/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@admin/components/activity-log/useModelActivityLog';
import { Form } from '@admin/components/form';
import FormField from '@admin/components/form/FormField';
import HeadingSmall from '@admin/components/heading-small';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { Head, router, usePage } from '@inertiajs/react';
import { Activity, Save, Trash2 } from 'lucide-react';
import { ReactNode, useEffect, useState } from 'react';

interface Props {
    settings: Record<string, string>; // key-value pairs from backend
}

// Skeleton Loader Components
const SkeletonField = () => (
    <div className="space-y-2">
        <div className="h-4 w-24 animate-pulse rounded bg-gray-200"></div>
        <div className="h-10 animate-pulse rounded bg-gray-200"></div>
    </div>
);

const SkeletonTextarea = () => (
    <div className="space-y-2">
        <div className="h-4 w-24 animate-pulse rounded bg-gray-200"></div>
        <div className="h-24 animate-pulse rounded bg-gray-200"></div>
    </div>
);

const SkeletonButton = () => <div className="h-10 w-32 animate-pulse rounded bg-gray-200"></div>;

const SkeletonCard = () => (
    <div className="space-y-2">
        <div className="h-4 w-32 animate-pulse rounded bg-gray-200"></div>
        <div className="h-20 animate-pulse rounded bg-gray-200"></div>
    </div>
);

export default function Edit({ settings }: Props) {
    const { props } = usePage();
    const externalErrors = (props as any)?.errors || {};
    const [isLoading, setIsLoading] = useState(true);
    const [deletingFile, setDeletingFile] = useState<string | null>(null);
    const activityLogCtl = useModelActivityLog();

    useEffect(() => {
        // Show skeleton for 1 second
        const timer = setTimeout(() => {
            setIsLoading(false);
        }, 500);

        return () => clearTimeout(timer);
    }, []);

    const handleSubmit = (data: any) => {
        // Ensure files are sent properly and avoid sending non-file logo values
        const payload: any = { ...data };
        if (!(payload.company_logo instanceof File)) {
            // If not a File object, omit to prevent clearing existing logo
            delete payload.company_logo;
        }

        router.post(route('settings.company.update'), { ...payload, _method: 'put' }, {
            forceFormData: true,
            onStart: () => {
                setIsLoading(true); // show skeleton while request is running
            },
            onSuccess: () => {
                setTimeout(() => {
                    setIsLoading(false);
                }, 500);
                // ✅ hide skeleton after success
            },
            onError: () => {
                setIsLoading(false); // also hide if failed
            },
        });
    };

    const handleDeleteFile = async (fileKey: string) => {
        if (!confirm(`Are you sure you want to delete the ${fileKey.replace('company_', '')}?`)) {
            return;
        }

        setDeletingFile(fileKey);
        
        try {
            const response = await fetch(route('settings.company.file.delete', { key: fileKey }), {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content || '',
                    'Accept': 'application/json',
                },
            });

            const data = await response.json();

            if (response.ok && data.success) {
                // Reload the page to refresh the settings
                router.reload();
            } else {
                alert(data.error || 'Failed to delete file');
            }
        } catch (error) {
            console.error('Error deleting file:', error);
            alert('Failed to delete file');
        } finally {
            setDeletingFile(null);
        }
    };

    // Default values from settings
    const defaultValues = {
        company_name: settings?.company_name || '',
        company_description: settings?.company_description || '',
        company_email: settings?.company_email || '',
        company_phone: settings?.company_phone || '',
        company_country: settings?.company_country || '',
        company_address: settings?.company_address || '',
        company_city: settings?.company_city || '',
        company_state: settings?.company_state || '',
        company_zip_code: settings?.company_zip_code || '',
        company_registration_number: settings?.company_registration_number || '',
        company_start_time: settings?.company_start_time || '',
        company_end_time: settings?.company_end_time || '',
        company_logo: settings?.company_logo || '', // File field default
        company_favicon: settings?.company_favicon || '', // File field default
    };

    // Skeleton Loader
    if (isLoading) {
        return (
            <>
                <Head title="Loading Settings..." />
                <SettingsLayout tab={'platform'}>
                    <Card className="space-y-4 px-5 py-3">
                        <div className="flex items-start justify-between">
                            <div className="space-y-2">
                                <div className="h-6 w-48 animate-pulse rounded bg-gray-200"></div>
                                <div className="h-4 w-64 animate-pulse rounded bg-gray-200"></div>
                            </div>
                            <div className="h-9 w-24 animate-pulse rounded bg-gray-200"></div>
                        </div>
                        <CardContent className="w-full p-0">
                            <div className="flex w-full flex-col items-start gap-4 lg:flex-row">
                                {/* Main Content Skeleton */}
                                <div className="w-full flex-1 space-y-6 rounded-lg border px-4 py-3">
                                    <div className="space-y-6">
                                        <SkeletonField />
                                        <SkeletonTextarea />
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <SkeletonField />
                                            <SkeletonField />
                                        </div>
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <SkeletonField />
                                            <SkeletonField />
                                        </div>
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <SkeletonField />
                                            <SkeletonField />
                                        </div>
                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <SkeletonField />
                                            <SkeletonField />
                                        </div>
                                    </div>
                                </div>

                                {/* Sidebar Skeleton */}
                                <div className="w-full space-y-6 rounded-lg border p-4 sm:p-6 lg:w-60 lg:flex-shrink-0 2xl:w-80">
                                    <SkeletonCard />
                                </div>
                            </div>

                            <div className="mt-2 flex items-center sm:mt-2">
                                <SkeletonButton />
                            </div>
                        </CardContent>
                    </Card>
                </SettingsLayout>
            </>
        );
    }

    return (
        <>
            <Head title="Edit Settings" />
            <SettingsLayout tab={'platform'}>
                <Card className="space-y-4 px-5 py-3">
                    <div className="mb-3 flex items-center justify-between border-b">
                        <HeadingSmall title="Company Information" description="Update your company's information" />

                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() =>
                                activityLogCtl.show({
                                    modelClass: 'Setting',
                                    title: 'General Settings Activity',
                                    action: 'general_settings_updated',
                                })
                            }
                        >
                            <Activity className="mr-1 h-4 w-4" /> Activity
                        </Button>
                    </div>
                    <CardContent className="w-full p-0">
                        <Form submitHandler={handleSubmit} defaultValues={defaultValues} externalErrors={externalErrors}>
                            <div className="flex w-full flex-col items-start gap-4 lg:flex-row">
                                <div className="w-full flex-1 space-y-6 rounded-lg border px-4 py-3">
                                    <div className="space-y-4 sm:space-y-6">
                                        <FormField type="text" name="company_name" label="Company Name" placeholder="Taskco Official" required />

                                        <FormField
                                            type="textarea"
                                            name="company_description"
                                            label="Description"
                                            placeholder="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam auctor, nisl nec ultrices ultrices, nunc nisl ultrices nunc, nec ultrices nunc nisl nec nunc."
                                            rows={4}
                                            required
                                        />

                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <FormField type="email" name="company_email" label="Email" placeholder="tamzeed@taskcodigital.com" required/>

                                            <FormField type="tel" name="company_phone" label="Phone Number" placeholder="(719) 869-6776 ×561" required/>
                                        </div>

                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <FormField type="text" name="company_country" label="Country" placeholder="Dhaka, Bangladesh" required/>

                                            <FormField type="text" name="company_address" label="Address" placeholder="7353 Paolo Street" required/>
                                        </div>

                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <FormField type="text" name="company_city" label="City" placeholder="Dhaka, Bangladesh" required/>

                                            <FormField type="text" name="company_state" label="State" placeholder="State" required/>
                                        </div>

                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <FormField type="text" name="company_zip_code" label="Zip/Post Code" placeholder="Dhaka, Bangladesh" required/>

                                            <FormField
                                                type="text"
                                                name="company_registration_number"
                                                label="Registration Number"
                                                placeholder="State"
                                                required
                                            />
                                        </div>

                                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                            <FormField type="time" name="company_start_time" label="Company Start Time" placeholder="10:00 AM" required/>
                                            <FormField type="time" name="company_end_time" label="Company End Time" placeholder="06:00 PM" required/>
                                        </div>
                                    </div>
                                </div>
                                {/* Company Logo Section */}
                                <div className="w-full space-y-6 rounded-lg border p-4 sm:p-6 lg:w-60 lg:flex-shrink-0 2xl:w-80">
                                    <div>
                                        <div className="mb-6 flex items-center justify-between">
                                            <div>
                                                <h3 className="mb-1 text-lg font-semibold text-gray-900">Company Logo</h3>
                                                <p className="text-sm text-gray-500">Upload company logo</p>
                                            </div>
                                            {settings?.company_logo && (
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    size="sm"
                                                    onClick={() => handleDeleteFile('company_logo')}
                                                    disabled={deletingFile === 'company_logo'}
                                                    className="text-red-600 hover:text-red-700 hover:border-red-300"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            )}
                                        </div>

                                        <FormField
                                            type="file"
                                            name="company_logo"
                                            accept="image/*"
                                            maxSize={5}
                                            preview={true}
                                            placeholder="Choose File"
                                            description="Recommended logo size is 500×200px"
                                            currentUrl={settings?.company_logo ? "/storage/" + settings.company_logo : undefined}
                                            placeholderUrl="/assets/logo/logo-v2.svg"
                                        />
                                    </div>
                                    <div>
                                        <div className="mb-6 flex items-center justify-between">
                                            <div>
                                                <h3 className="mb-1 text-lg font-semibold text-gray-900">Company Favicon</h3>
                                                <p className="text-sm text-gray-500">Upload company favicon</p>
                                            </div>
                                            {settings?.company_favicon && (
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    size="sm"
                                                    onClick={() => handleDeleteFile('company_favicon')}
                                                    disabled={deletingFile === 'company_favicon'}
                                                    className="text-red-600 hover:text-red-700 hover:border-red-300"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            )}
                                        </div>
                                        <FormField
                                            type="file"
                                            name="company_favicon"
                                            accept="image/*"
                                            maxSize={5}
                                            preview={true}
                                            placeholder="Choose File"
                                            description="Recommended logo size is 500×200px"
                                            currentUrl={settings?.company_favicon ? "/storage/" + settings.company_favicon : undefined}
                                            placeholderUrl="/assets/logo/logo-v2.svg"
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="mt-2 flex items-center sm:mt-2">
                                <Button type="submit" className="w-full px-6 py-2 sm:w-auto sm:px-8">
                                    <Save className="h-4 w-4" />
                                    Save Changes
                                </Button>
                            </div>
                        </Form>
                    </CardContent>
                </Card>
            </SettingsLayout>
            <ActivityLogSidebar
                open={activityLogCtl.open}
                onOpenChange={activityLogCtl.setOpen}
                modelClass={activityLogCtl.modelClass}
                modelId={activityLogCtl.modelId}
                title={activityLogCtl.title}
                action={activityLogCtl.action}
                settingKey={activityLogCtl.settingKey}
                onClearFilters={() => activityLogCtl.clearFilters?.()}
            />
        </>
    );
}

Edit.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: route('settings.company.edit') },
            { title: 'Edit', href: '#' },
        ]}
        title="Edit Settings"
    >
        {page}
    </AppLayout>
);
