"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Building2, Save, X, Upload, MapPin, Check, AlertCircle, Camera, UserCircle } from "lucide-react";
import {
  useGetShopRegistrationQuery,
  useCreateShopRegistrationMutation,
  useUpdateShopRegistrationMutation,
} from "@/redux/apis/shopApi";
import GoogleMapLocationPicker, { LocationDetails } from "../GoogleMapLocationPicker";

export default function ShopRegistrationForm({ onClose }: { onClose?: () => void }) {
  const router = useRouter();
  const { data, isLoading } = useGetShopRegistrationQuery();
  const [createShop] = useCreateShopRegistrationMutation();
  const [updateShop] = useUpdateShopRegistrationMutation();

  const [formData, setFormData] = useState({
    ownerName: "",
    shopName: "",
    emailId: "",
    shopNo: "",
    complexName: "",
    street: "",
    landmark: "",
    city: "",
    pinCode: "",
    mobileNumber: "",
    mobileNumber2: "",
    shopGoogleLocation: "",
  });


  const [files, setFiles] = useState<Record<string, File | File[] | null>>({
    shopPhotos: null,
    selfiePhoto: null,
    shopactDocument: null,
    udyamAadharDocument: null,
    gstDocument: null,
    aadharCard: null,
    panCard: null,
    ownerPassportPhoto: null,
  });

  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    if (data?.success && data.data) {
      setFormData({
        ownerName: data.data.ownerName || "",
        shopName: data.data.shopName || "",
        emailId: data.data.emailId || "",
        shopNo: data.data.shopNo || "",
        complexName: data.data.complexName || "",
        street: data.data.street || "",
        landmark: data.data.landmark || "",
        city: data.data.city || "",
        pinCode: data.data.pinCode || "",
        mobileNumber: data.data.mobileNumber || "",
        mobileNumber2: data.data.mobileNumber2 || "",
        shopGoogleLocation: data.data.shopGoogleLocation || "",
      });
    }
  }, [data]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleLocationChange = (location: string, lat?: number, lng?: number, details?: LocationDetails) => {
    setFormData(prev => ({
      ...prev,
      shopGoogleLocation: location,
      // Auto-fill city and pincode if available
      city: details?.city || details?.locality || prev.city,
      pinCode: details?.pincode || prev.pinCode,
      // If we have a formatted address, we can try to extract street if street is empty
      street: !prev.street && details?.address ? details.address.split(',')[0] : prev.street
    }));
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name } = e.target;
    if (name === "shopPhotos" && e.target.files) {
      setFiles({ ...files, [name]: Array.from(e.target.files) });
    } else if (e.target.files?.[0]) {
      setFiles({ ...files, [name]: e.target.files[0] });
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const submitData = new FormData();

      Object.keys(formData).forEach((key) => {
        if (formData[key as keyof typeof formData]) {
          submitData.append(key, formData[key as keyof typeof formData]);
        }
      });

      if (files.shopPhotos && Array.isArray(files.shopPhotos)) {
        files.shopPhotos.forEach((file) => {
          submitData.append("shopPhotos", file);
        });
      }

      Object.keys(files).forEach((key) => {
        if (key !== "shopPhotos" && files[key]) {
          const file = Array.isArray(files[key]) ? files[key][0] : files[key];
          if (file) submitData.append(key, file);
        }
      });

      if (data?.success && data.data?.id) {
        await updateShop(submitData).unwrap();
      } else {
        await createShop(submitData).unwrap();
      }
      if (onClose) onClose();
      router.refresh();
    } catch (error) {
      console.error("Error saving shop registration:", error);
      alert("Failed to save shop registration");
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return <div className="text-center py-4">Loading...</div>;
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Owner Name *
          </label>
          <input
            type="text"
            name="ownerName"
            value={formData.ownerName}
            onChange={handleChange}
            required
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Shop Name *
          </label>
          <input
            type="text"
            name="shopName"
            value={formData.shopName}
            onChange={handleChange}
            required
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Email <span className="text-theme-muted text-xs ms-1">(Optional)</span>
          </label>
          <input
            type="email"
            name="emailId"
            value={formData.emailId}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
            placeholder="Enter shop email"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Mobile Number <span className="text-theme-muted text-xs ms-1">(Optional)</span>
          </label>
          <input
            type="tel"
            name="mobileNumber"
            value={formData.mobileNumber}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
            placeholder="Enter shop mobile number"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Shop No
          </label>
          <input
            type="text"
            name="shopNo"
            value={formData.shopNo}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Complex Name
          </label>
          <input
            type="text"
            name="complexName"
            value={formData.complexName}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Street
          </label>
          <input
            type="text"
            name="street"
            value={formData.street}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            City
          </label>
          <input
            type="text"
            name="city"
            value={formData.city}
            onChange={handleChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>


        <div className="col-span-full">
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Shop Location (Google Maps) *
          </label>
          <GoogleMapLocationPicker
            value={formData.shopGoogleLocation}
            onChange={handleLocationChange}
            placeholder="Search for your shop or pick on map..."
            height="400px"
          />
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Owner Passport Size Photo *
          </label>
          <div className="flex items-center gap-4">
            <div className="flex-1">
              <input
                type="file"
                name="ownerPassportPhoto"
                accept="image/*"
                onChange={handleFileChange}
                className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
              />
            </div>
            <button
              type="button"
              className="p-3 bg-theme-input border border-primary-500/20 rounded-xl text-theme-secondary hover:text-primary-500 transition-colors"
              title="Click Photo"
            >
              <Camera className="w-5 h-5" />
            </button>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Selfie Photo
          </label>
          <div className="flex items-center gap-4">
            <div className="flex-1">
              <input
                type="file"
                name="selfiePhoto"
                accept="image/*"
                onChange={handleFileChange}
                className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
              />
            </div>
            <button
              type="button"
              className="p-3 bg-theme-input border border-primary-500/20 rounded-xl text-theme-secondary hover:text-primary-500 transition-colors"
              title="Take Selfie"
            >
              <Camera className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>

      <div className="grid md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Shopact Document
          </label>
          <input
            type="file"
            name="shopactDocument"
            accept="image/*,application/pdf"
            onChange={handleFileChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Udyam Aadhar Document
          </label>
          <input
            type="file"
            name="udyamAadharDocument"
            accept="image/*,application/pdf"
            onChange={handleFileChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            GST Document
          </label>
          <input
            type="file"
            name="gstDocument"
            accept="image/*,application/pdf"
            onChange={handleFileChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            Aadhar Card
          </label>
          <input
            type="file"
            name="aadharCard"
            accept="image/*,application/pdf"
            onChange={handleFileChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-theme-secondary mb-1">
            PAN Card
          </label>
          <input
            type="file"
            name="panCard"
            accept="image/*,application/pdf"
            onChange={handleFileChange}
            className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
          />
        </div>
      </div>

      <div className="flex gap-3 pt-4">
        <button
          type="submit"
          disabled={isSubmitting}
          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-primary-500 text-white rounded-xl hover:bg-primary-600 transition-colors disabled:opacity-50"
        >
          <Save className="w-4 h-4" />
          {isSubmitting ? "Saving..." : "Save"}
        </button>
        {onClose && (
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 bg-theme-input border border-primary-500/20 text-theme-secondary rounded-xl hover:bg-primary-500/10 transition-colors"
          >
            <X className="w-4 h-4" />
          </button>
        )}
      </div>
    </form>
  );
}



