"use client";

import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiCall } from "@/utils/callApi";
import { X } from "lucide-react";

interface StateItem {
  _id: string;
  name: string;
  code: string;
  country: string;
}
interface StateItem {
  _id: string;
  name: string;
  code: string;
  country: string;
}

interface StateResponse {
  data: {
    data: StateItem[];
  };
}

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  formData: any;
  location: any;
  setFormData: React.Dispatch<React.SetStateAction<any>>;
  checkValidation: (key: string, value: string) => void;
  validationError: {
    phone_number: string | null;
    name: string | null;
    address: string | null;
    email?: string | null
  };
  handleSubmit: (e: React.FormEvent) => void;
  loading: boolean;
}
interface response {
  data: {
    data: {};
  };
}
const LeadFormDialog = ({
  open,
  onOpenChange,
  formData,
  setFormData,
  checkValidation,
  validationError,
  handleSubmit,
  location,
  loading,
}: Props) => {
  const [states, setStates] = useState<StateItem[]>([]);

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

    checkValidation(field, value);
  };
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        e.stopPropagation();
      }
    };

    document.addEventListener("keydown", handleKeyDown, true);

    return () => {
      document.removeEventListener("keydown", handleKeyDown, true);
    };
  }, []);
  
  // const callStateApi = async () => {
  //   try {
  //     const response = await apiCall<StateResponse>("/api/states", {
  //       method: "GET",
  //     });

  //     console.log("State API Response:", response);

  //     // Adjust according to your apiCall helper response
  //     const stateData = response?.data?.data || response?.data || [];

  //     setStates(Array.isArray(stateData) ? stateData : []);
  //   } catch (error) {
  //     console.error("Error fetching states:", error);
  //   }
  // };

  // useEffect(() => {
  //   callStateApi();
  // }, []);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="fixed bottom-0 left-0 right-0 top-0 flex items-center justify-center overflow-auto p-2">
        <div className="m-auto w-full max-w-[600px] rounded-lg bg-white">
          <DialogHeader className="px-4 pb-2 pt-4">
            <DialogTitle>Submit your inquiry</DialogTitle>
            <span onClick={() => onOpenChange(false)}>
              {location == "others" && <X className="text-white" />}
            </span>
          </DialogHeader>

          <div className="p-6">
            <form onSubmit={handleSubmit} className="space-y-4 p-4 pb-4">
              {/* Name */}
              <div>
                <Label>Name <span className="text-red-500">*</span></Label>
                <Input
                  value={formData.name || ""}
                  onChange={(e) => set("name", e.target.value)}
                  required
                />
                {validationError?.name && (
                  <span className="text-sm text-red-500">
                    {validationError.name}
                  </span>
                )}
              </div>

              {/* Phone */}
              <div>
                <Label>Phone Number <span className="text-red-500">*</span></Label>
                <Input
                  type="tel"
                  value={formData.phone_number || ""}
                  onChange={(e) => {
                    const value = e.target.value.replace(/\D/g, "");
                    set("phone_number", value);
                  }}
                  maxLength={10}
                  required
                />

                {validationError?.phone_number && (
                  <span className="text-sm text-red-500">
                    {validationError.phone_number}
                  </span>
                )}
              </div>

              {/* State */}
              {/* <div>
                <Label>State *</Label>

                <select
                  value={formData.state || ""}
                  onChange={(e) =>
                    set("state", e.target.value)
                  }
                  className="w-full h-10 px-3 border rounded-md bg-background"
                  required
                >
                  <option value="">
                    Select State
                  </option>

                  {states.map((item) => (
                    <option
                      key={item._id}
                      value={item._id}
                    >
                      {item.name}
                    </option>
                  ))}
                </select>
              </div> */}    

              {/* Email */}
              <div>
                <Label>Email</Label>
                <Input
                  value={formData.email || ""}
                  onChange={(e) => set("email", e.target.value)}
                />
                {validationError?.email && (
                  <span className="text-sm text-red-500">
                    {validationError.email}
                  </span>
                )}
              </div>          

              {/* Address */}
              <div>
                <Label>Location <span className="text-red-500">*</span></Label>
                <Input
                  value={formData.address || ""}
                  onChange={(e) => set("address", e.target.value)}
                  required
                />
                {validationError?.address && (
                  <span className="text-sm text-red-500">
                    {validationError.address}
                  </span>
                )}
              </div>              

              {/* Submit */}
              <div className="flex justify-end pt-2">
                <Button type="submit" disabled={loading}>
                  {loading ? "Saving..." : "Continue"}
                </Button>
              </div>
            </form>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default React.memo(LeadFormDialog);
