import React from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Switch } from "../../../../../src/components/ui/switch";
import { X } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingStore: any;
  formData: any;
  setFormData: React.Dispatch<React.SetStateAction<any>>;
  handleSubmit: (e: React.FormEvent) => void;
  loading: boolean;
  resetForm: () => void;
}

const StoreFormDialog = ({
  open,
  onOpenChange,
  editingStore,
  formData,
  setFormData,
  handleSubmit,
  loading,
  resetForm,
}: Props) => {
  const [phoneError, setPhoneError] = React.useState<string>("");

  const set = (field: string, value: any) =>
    setFormData((prev: any) => ({ ...prev, [field]: value }));

  const validatePhoneNumber = (phone: string): boolean => {
    // Remove any non-digit characters for validation
    const cleanPhone = phone.replace(/\D/g, '');
    
    if (cleanPhone.length === 0) {
      setPhoneError("");
      return true;
    }
    
    if (cleanPhone.length < 10) {
      setPhoneError("Phone number must be at least 10 digits");
      return false;
    }
    
    if (cleanPhone.length > 15) {
      setPhoneError("Phone number cannot exceed 15 digits");
      return false;
    }
    
    // Optional: Check for valid Indian phone number pattern
    // const phoneRegex = /^[6-9]\d{9}$/;
    // if (!phoneRegex.test(cleanPhone)) {
    //   setPhoneError("Please enter a valid phone number");
    //   return false;
    // }
    
    setPhoneError("");
    return true;
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    // Allow only digits, plus sign, and hyphens (for formatting)
    const formattedValue = value.replace(/[^\d+ -]/g, '');
    set("phone", formattedValue);
    
    // Validate the phone number (remove non-digits for validation)
    const cleanValue = formattedValue.replace(/\D/g, '');
    validatePhoneNumber(cleanValue);
  };

  const handlePhoneBlur = () => {
    // Format phone number on blur if needed
    const cleanValue = formData.phone.replace(/\D/g, '');
    if (cleanValue.length >= 10 && cleanValue.length <= 15) {
      // Optional: Format as +91 XXXXX XXXXX for Indian numbers
      // Format based on your requirements
      let formattedPhone = cleanValue;
      
      // Example: Format as +91 XXXXX XXXXX for 10-digit numbers
      // if (cleanValue.length === 10) {
      //   formattedPhone = `+91 ${cleanValue.slice(0, 5)} ${cleanValue.slice(5)}`;
      // }
      
      // set("phone", formattedPhone);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
          <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 bg-white p-0 shadow-lg dark:bg-[#1f2a37] dark:text-white">

            <DialogHeader>
              <DialogTitle>{editingStore ? "Edit Store" : "Add New Store"}</DialogTitle>
              <X
                className="h-6 w-6 p-1 text-white cursor-pointer"
                onClick={() => { onOpenChange(false); resetForm(); }}
              />
            </DialogHeader>

            <form onSubmit={handleSubmit} className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
              <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">

                {/* Name */}
                <div>
                  <Label className="mb-2 block" htmlFor="name">
                    Store Name <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={e => set("name", e.target.value)}
                    placeholder="e.g., Dulhe Saheb - CG Road"
                    required
                  />
                </div>

                {/* Address */}
                <div>
                  <Label className="mb-2 block" htmlFor="address">
                    Address <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="address"
                    value={formData.address}
                    onChange={e => set("address", e.target.value)}
                    placeholder="e.g., 123 MG Road, Near City Mall, Kolkata, West Bengal"
                    required
                  />
                </div>

                {/* Phone */}
                <div>
                  <Label className="mb-2 block" htmlFor="phone">
                    Phone Number <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    id="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={handlePhoneChange}
                    onBlur={handlePhoneBlur}
                    placeholder="e.g., 9876543210"
                    required
                    minLength={10}
                    maxLength={15}
                    className={phoneError ? "border-red-500 focus:ring-red-500" : ""}
                  />
                  {phoneError && (
                    <p className="mt-1 text-xs text-red-500">{phoneError}</p>
                  )}
                  <p className="mt-1 text-xs text-gray-500">
                    Enter 10-15 digit phone number (numbers only)
                  </p>
                </div>

                {/* Store Timings */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="mb-2 block" htmlFor="openTime">
                      Open Time <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      id="openTime"
                      type="time"
                      value={formData.openTime}
                      onChange={e => set("openTime", e.target.value)}
                      required
                    />
                  </div>

                  <div>
                    <Label className="mb-2 block" htmlFor="closeTime">
                      Close Time <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      id="closeTime"
                      type="time"
                      value={formData.closeTime}
                      onChange={e => set("closeTime", e.target.value)}
                      required
                    />
                  </div>
                </div>

                {/* Active Status */}
                <div className="flex items-center gap-6">
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={formData.isActive}
                      onCheckedChange={checked => set("isActive", checked)}
                      className="peer data-[state=checked]:border-purple-300 data-[state=unchecked]:border-gray-400 data-[state=unchecked]:bg-gray-100"
                    />
                    <Label>{formData.isActive ? "Active" : "Inactive"}</Label>
                  </div>
                </div>

              </div>

              {/* Footer */}
              <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                <Button type="button" variant="outline" onClick={() => { onOpenChange(false); resetForm(); }}>
                  Cancel
                </Button>
                <Button 
                  type="submit" 
                  disabled={loading || !!phoneError || (formData.phone?.replace(/\D/g, '').length > 0 && 
                    (formData.phone?.replace(/\D/g, '').length < 10 || 
                     formData.phone?.replace(/\D/g, '').length > 15))}
                >
                  {editingStore
                    ? (loading ? "Updating..." : "Update")
                    : (loading ? "Creating..." : "Create")
                  }
                </Button>
              </div>
            </form>

          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default React.memo(StoreFormDialog);