import { type BreadcrumbItem, type SharedData } from '@/types';
import { Transition } from '@headlessui/react';
import { Head, useForm, usePage } from '@inertiajs/react';
import { FormEventHandler, useEffect, useState } from 'react';

import HeadingSmall from '@/components/heading-small';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import SettingsLayout from '@/layouts/settings/layout';

import { AccountCircleOutlined } from '@mui/icons-material';
import { Loader, Uploader } from 'rsuite';
import 'rsuite/dist/rsuite-no-reset.min.css';
import { Alert } from '@mui/material';

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Profile settings',
        href: '/settings/profile',
    },
];

type BusinessForm = {
    business_name: string;
    business_logo: string;
};

export default function BusinessProfile({ mustVerifyEmail, status }: { mustVerifyEmail: boolean; status?: string }) {
    const { auth } = usePage<SharedData>().props;

    const { data, setData, patch, errors, processing, recentlySuccessful } = useForm<Required<BusinessForm>>({
        business_name: auth.user.business_name,
        business_logo: auth.user.business_logo,
    });

    const [uploading, setUploading] = useState(false);
    const [fileInfo, setFileInfo] = useState(null);

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        patch(route('business.update'), {
            preserveScroll: true,
        });
    };
    function formatIndianMobileNumber(mobile) {
        // Remove all spaces, dashes, parentheses
        mobile = mobile.replace(/[\s\-()]/g, '');

        // If it starts with +91 and followed by 10 digits
        if (/^\+91\d{10}$/.test(mobile)) {
            return mobile.slice(0, 3) + ' ' + mobile.slice(3);
        }

        // If it starts with 91 and followed by 10 digits
        if (/^91\d{10}$/.test(mobile)) {
            return '+91 ' + mobile.slice(2);
        }

        // If it's a valid 10-digit number
        if (/^\d{10}$/.test(mobile)) {
            return '+91 ' + mobile;
        }

        // Invalid number
        return null;
    }

    function previewFile(file, callback) {
        const reader = new FileReader();
        reader.onloadend = () => {
            callback(reader.result);
        };
        reader.readAsDataURL(file);
    }

    useEffect(() => {
        if(data.business_logo){
            setFileInfo(data.business_logo);
        }
    },[data.business_logo])

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Profile settings" />
            {!data.business_name && (
                <Alert severity="error">Must Need To Fill Business Details to Continue.</Alert>
            )}
            
    
            <SettingsLayout>
                <div className="space-y-6">
                    <HeadingSmall title="Business Information" description="Update your business information" />
                    

                    <form onSubmit={submit} className="space-y-6">
                        <div className="grid gap-2">
                            <Label htmlFor="business_name">Business Name</Label>

                            <Input
                                id="business_name"
                                className="mt-1 block w-full"
                                value={data.business_name}
                                onChange={(e) => setData('business_name', e.target.value)}
                                required
                                autoComplete="business_name"
                                placeholder="business name"
                            />

                            <InputError className="mt-2" message={errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="business_logo">Business Logo</Label>
                            <Uploader
                                accept="image/*" 
                                fileListVisible={false}
                                autoUpload={false}
                                listType="picture"
                                onChange={(response, file) => {
                                    if (response.length > 0) {
                                        previewFile(response[0].blobFile, (value) => {
                                            setData('business_logo', value)
                                            setFileInfo(value);
                                        });
                                    }
                                }}
                                multiple={false}
                                onError={() => {
                                    setFileInfo(null);
                                    setUploading(false);
                                }}
                            >
                                <button type='button' style={{ width: 150, height: 150 }}>
                                    {uploading && <Loader backdrop center />}
                                    {fileInfo ? (
                                        <img src={fileInfo} width="100%" height="100%" />
                                    ) : (
                                        <AccountCircleOutlined style={{ fontSize: 80 }} />
                                    )}
                                </button>
                            </Uploader>
                        </div>

                        <div className="flex items-center gap-4">
                            <Button disabled={processing}>Save</Button>

                            <Transition
                                show={recentlySuccessful}
                                enter="transition ease-in-out"
                                enterFrom="opacity-0"
                                leave="transition ease-in-out"
                                leaveTo="opacity-0"
                            >
                                <p className="text-sm text-neutral-600">Saved</p>
                            </Transition>
                        </div>
                    </form>
                </div>
            </SettingsLayout>
        </AppLayout>
    );
}
