'use client';
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useGlobalContext } from '@/context/Provider';
import countries from '@/utils/CountryCode.json';
import CountryPickerModal from '@/components/countrycode/page';

interface CustomerDetails {
    name: string;
    phone?: string;
    email?: string;
    gst?: string;
    country_code?: string;
}

interface CustomerModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSave: (details: CustomerDetails) => void;
    initialData?: CustomerDetails;
}

export default function CustomerModal({ isOpen, onClose, onSave, initialData }: CustomerModalProps) {
    const [formData, setFormData] = useState<CustomerDetails>({
        name: '',
        phone: '',
        email: '',
        gst: '',
        country_code: '+91'
    });
    const [countryValue, setCountryValue] = useState<any>(countries?.[97]);

    const { Toast } = useGlobalContext();

    useEffect(() => {
        if (isOpen && initialData) {
            setFormData(initialData);
            // Find matching country from initialData country_code
            if (initialData.country_code) {
                const code = initialData.country_code.replace('+', '');
                const match = countries.find((c: any) => c.dial_code === code || c.dial_code === initialData.country_code);
                if (match) setCountryValue(match);
            }
        } else if (isOpen) {
            setFormData({ name: '', phone: '', email: '', gst: '', country_code: '+91' });
            setCountryValue(countries?.[97]);
        }
    }, [isOpen, initialData]);

    const handleCountryChange = (country: any) => {
        setCountryValue(country);
        setFormData(prev => ({ ...prev, country_code: `+${country.dial_code}` }));
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSave = () => {
        if (!formData.name.trim()) {
            Toast.error('Name is required');
            return;
        }
        onSave(formData);
        onClose();
    };

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[450px] p-8 rounded-3xl border-0 shadow-2xl">
                <DialogHeader className="mb-6">
                    <DialogTitle className="text-2xl font-bold text-gray-800">Customer Details</DialogTitle>
                </DialogHeader>
                <div className="grid gap-6 py-2">
                    <div className="grid grid-cols-3 items-center gap-4">
                        <Label htmlFor="name" className="text-right text-[var(--orange-500)] font-bold">
                            Name *
                        </Label>
                        <Input
                            id="name"
                            name="name"
                            value={formData.name}
                            onChange={handleChange}
                            className="col-span-2 h-12 rounded-xl bg-white border-gray-200 placeholder:text-gray-300"
                            placeholder="John Doe"
                        />
                    </div>
                    <div className="grid grid-cols-3 items-center gap-4">
                        <Label htmlFor="phone" className="text-right text-[var(--orange-500)] font-bold">
                            Phone
                        </Label>
                        <div className="col-span-2 flex items-center h-12 rounded-xl border border-gray-200 bg-white overflow-hidden">
                            <div className="shrink-0 border-r border-gray-200">
                                <CountryPickerModal
                                    setValue={handleCountryChange}
                                    value={countryValue}
                                    triggerClassName="w-auto border-0 rounded-none h-[46px] px-3 py-2"
                                />
                            </div>
                            <Input
                                id="phone"
                                name="phone"
                                value={formData.phone}
                                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                                    const phoneNumber = e.target.value.replace(/\D/g, '');
                                    setFormData(prev => ({ ...prev, phone: phoneNumber }));
                                }}
                                className="h-full border-0 rounded-none bg-transparent placeholder:text-gray-300 flex-1 focus-visible:ring-0 focus-visible:ring-offset-0"
                                placeholder="Enter your phone number"
                                maxLength={countryValue?.max_length || 15}
                            />
                        </div>
                    </div>
                    <div className="grid grid-cols-3 items-center gap-4">
                        <Label htmlFor="email" className="text-right text-[var(--orange-500)] font-bold">
                            Email
                        </Label>
                        <Input
                            id="email"
                            name="email"
                            type="email"
                            value={formData.email}
                            onChange={handleChange}
                            className="col-span-2 h-12 rounded-xl bg-white border-gray-200 placeholder:text-gray-300"
                            placeholder="john@example.com"
                        />
                    </div>
                    <div className="grid grid-cols-3 items-center gap-4">
                        <Label htmlFor="gst" className="text-right text-[var(--orange-500)] font-bold">
                            GST No.
                        </Label>
                        <Input
                            id="gst"
                            name="gst"
                            value={formData.gst}
                            onChange={handleChange}
                            className="col-span-2 h-12 rounded-xl bg-white border-gray-200 placeholder:text-gray-300"
                            placeholder="GSTIN12345"
                        />
                    </div>
                </div>
                <DialogFooter className="mt-6">
                    <Button
                        onClick={handleSave}
                        className="bg-[var(--orange-500)] text-white hover:bg-[var(--orange-500)]/90 h-12 px-8 rounded-xl font-bold shadow-lg shadow-[var(--orange-500)]/20"
                    >
                        Save Details
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
