"use client";

import { useState, useEffect } from "react";
import { ShowcaseSection } from "../../../../../../src/components/Layouts/showcase-section";
import InputGroup from "../../../../../../src/components/FormElements/InputGroup";
import { TextAreaGroup } from "../../../../../../src/components/FormElements/InputGroup/text-area";
import { UploadIcon } from "../../../../../../src/assets/icons";
import Image from "next/image";
import { toast } from "sonner";

interface GeneralSettings {
  _id?: string;
  appName: string;
  phoneNumber: string;
  email: string;
  location: string;
  logo?: string;
  footerLogo?: string;
  favicon?: string;
  facebookLink?: string;
  instagramLink?: string;
  youtubeLink?:string;
  statementContent?:string;
  printerestLink?:string;
  whatsappNumber?: string;
  isActive: boolean;
}

export function GeneralSettingsForm() {
  const [settings, setSettings] = useState<GeneralSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  // Fetch current settings
  useEffect(() => {
    fetchSettings();
  }, []);
   const validatePhoneNumber = (phone: string) => {
  return /^[0-9+\-\s()]{10,15}$/.test(phone);
};

const validateWhatsappNumber = (phone: string) => {
  return /^[0-9+\-\s()]{10,15}$/.test(phone);
};

const validateLocation = (location: string) => {
  return /^[A-Za-z0-9\s,.-]{3,100}$/.test(location);
};

const validateEmail = (email: string) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};
  const fetchSettings = async () => {
    try {
      const response = await fetch('/api/general-settings');
      const result = await response.json();

      if (result.success) {
        setSettings(result.data);
      } else {
        setMessage({ type: 'error', text: 'Failed to load settings' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to load settings' });
    } finally {
      setLoading(false);
    }
  };

  // const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
  //   e.preventDefault();
  //   setSaving(true);
  //   setMessage(null);

  //   try {
  //     const formData = new FormData(e.currentTarget);

  //     const response = await fetch('/api/general-settings', {
  //       method: 'PUT',
  //       body: formData,
  //     });

  //     const result = await response.json();

  //     if (result.success) {
  //       setSettings(result.data);
  //       setMessage({ type: 'success', text: 'Settings updated successfully!' });
  //     } else {
  //       setMessage({ type: 'error', text: result.error || 'Failed to update settings' });
  //     }
  //   } catch (error) {
  //     setMessage({ type: 'error', text: 'Failed to update settings' });
  //   } finally {
  //     setSaving(false);
  //   }
  // };
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  setSaving(true);
  setMessage(null);

  const formData = new FormData(e.currentTarget);

  const newErrors: Record<string, string> = {};

  const phoneNumber = formData.get("phoneNumber")?.toString() || "";
  const whatsappNumber = formData.get("whatsappNumber")?.toString() || "";
  const location = formData.get("location")?.toString() || "";
  const email = formData.get("email")?.toString() || "";

  // Phone validation
  if (!validatePhoneNumber(phoneNumber)) {
    newErrors.phoneNumber =
      "Enter a valid phone number (10-15 digits)";
  }

  // WhatsApp validation
  if (whatsappNumber && !validateWhatsappNumber(whatsappNumber)) {
    newErrors.whatsappNumber =
      "Enter a valid WhatsApp number";
  }

  // Location validation
  if (!validateLocation(location)) {
    newErrors.location =
      "Location can contain only letters, numbers, spaces, comma, dot and hyphen";
  }

  // Email validation
  if (!validateEmail(email)) {
    newErrors.email = "Enter a valid email address";
  }

  // Stop submit if errors exist
  if (Object.keys(newErrors).length > 0) {
    setErrors(newErrors);
    setSaving(false);
    return;
  }

  setErrors({});

  try {
    const response = await fetch('/api/general-settings', {
      method: 'PUT',
      body: formData,
    });

    const result = await response.json();

    if (result.success) {
      window.dispatchEvent(new Event('logo-updated'))
      setSettings(result.data);
      setMessage({
        type: 'success',
        text: 'Settings updated successfully!'
      });
    } else {
      setMessage({
        type: 'error',
        text: result.error || 'Failed to update settings'
      });
    }
  } catch (error) {
    setMessage({
      type: 'error',
      text: 'Failed to update settings'
    });
  } finally {
    setSaving(false);
  }
};

  useEffect(() => {
    if(!message) return
    const { type, text } = message || {}
    type === 'error' ? toast.error(text) : toast.success(text)
  }, [message])

  const handleImageChange = (fieldName: string, file: File | null) => {
    if (settings) {
      setSettings({
        ...settings,
        [fieldName]: file ? URL.createObjectURL(file) : undefined
      });
    }
  };

  if (loading) {
    return (
      <ShowcaseSection title="General Settings" className="!p-7">
        <div className="flex items-center justify-center py-8">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
            <p className="mt-2 text-sm text-gray-6">Loading settings...</p>
          </div>
        </div>
      </ShowcaseSection>
    );
  }

  if (!settings) {
    return (
      <ShowcaseSection title="General Settings" className="!p-7">
        <div className="text-center py-8">
          <p className="text-red-500">Failed to load settings</p>
        </div>
      </ShowcaseSection>
    );
  }

  return (
    <ShowcaseSection title="General Settings" className="!p-7">
      {/* {message && (
        <div className={`mb-4 p-3 rounded-lg ${message.type === 'success' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'}`}>
          {message.text}
        </div>
      )} */}

      <form onSubmit={handleSubmit} encType="multipart/form-data">
        {/* Basic Information */}
        <div className="mb-5.5">
          <h3 className="mb-4 text-lg font-semibold text-dark dark:text-white">Basic Information</h3>

          <div className="grid grid-cols-1 gap-5.5 sm:grid-cols-2">
            <InputGroup
              type="text"
              name="appName"
              label="App Name"
              placeholder="Your App Name"
              defaultValue={settings.appName}
              required
              height="sm"
            />
            <div>
              <InputGroup
                type="text"
                name="phoneNumber"
                label="Phone Number"
                placeholder="+1 234 567 8900"
                defaultValue={settings.phoneNumber}
                required
                height="sm"
              />
              {errors.phoneNumber && (
                <p className="mt-1 text-sm text-red-500">
                  {errors.phoneNumber}
                </p>
              )}
            </div>

              <div>
                <InputGroup
                  type="email"
                  name="email"
                  label="Email Address"
                  placeholder="contact@yourapp.com"
                  defaultValue={settings.email}
                  required
                  height="sm"
                />
                {errors.email && (
                  <p className="mt-1 text-sm text-red-500">
                    {errors.email}
                  </p>
                )}
              </div>

           <div>
              <InputGroup
                type="text"
                name="location"
                label="Location"
                placeholder="Your Location"
                defaultValue={settings.location}
                required
                height="sm"
              />
              {errors.location && (
                <p className="mt-1 text-sm text-red-500">
                  {errors.location}
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Social Links */}
        <div className="mb-5.5">
          <h3 className="mb-4 text-lg font-semibold text-dark dark:text-white">Social Links</h3>

          <div className="grid grid-cols-1 gap-5.5 sm:grid-cols-2">
            <InputGroup
              type="url"
              name="facebookLink"
              label="Facebook Link"
              placeholder="https://facebook.com/yourpage"
              defaultValue={settings.facebookLink || ''}
              height="sm"
            />

            <InputGroup
              type="url"
              name="instagramLink"
              label="Instagram Link"
              placeholder="https://instagram.com/yourpage"
              defaultValue={settings.instagramLink || ''}
              height="sm"
            />
            <InputGroup
              type="url"
              name="youtubeLink"
              label="Youtube Link"
              placeholder="https://youtube.com/yourpage"
              defaultValue={settings.youtubeLink || ''}
              height="sm"
            />
            <InputGroup
              type="url"
              name="printerestLink"
              label="Printerest Link"
              placeholder="https://printerest.com/yourpage"
              defaultValue={settings.printerestLink || ''}
              height="sm"
            />
            <div>
              <InputGroup
                type="text"
                name="whatsappNumber"
                label="WhatsApp Number"
                placeholder="+1234567890"
                defaultValue={settings.whatsappNumber || ''}
                height="sm"
              />
              {errors.whatsappNumber && (
                <p className="mt-1 text-sm text-red-500">
                  {errors.whatsappNumber}
                </p>
              )}
            </div>
          </div>
        </div>
        <div className="mb-5.5">
          <h3 className="mb-4 text-lg font-semibold text-dark dark:text-white">Header Statement</h3>
           <InputGroup
                type="text"
                name="statementContent"
                label="Header Statement"
                placeholder="Header Statement"
                defaultValue={settings.statementContent}
                required
                height="sm"
              />
        </div>
        {/* Images */}
        <div className="mb-5.5">
          <h3 className="mb-4 text-lg font-semibold text-dark dark:text-white">Images & Assets</h3>

          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {/* Logo */}
            <div>
              <label className="mb-2.5 block text-sm font-medium text-dark dark:text-white">
                Logo
              </label>
              <div className="relative">               
                <div className="relative block w-full rounded-xl border border-dashed border-gray-4 bg-gray-2 hover:border-primary dark:border-dark-3 dark:bg-dark-2 dark:hover:border-primary">
                  <input
                    type="file"
                    name="logo"
                    accept="image/*"
                    onChange={(e) => handleImageChange('logo', e.target.files?.[0] || null)}
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                  />
                  <div className="flex cursor-pointer flex-col items-center justify-center p-4">
                    <div className="flex size-10 items-center justify-center rounded-full border border-stroke bg-white dark:border-dark-3 dark:bg-gray-dark">
                      <UploadIcon />
                    </div>
                    <p className="mt-2 text-xs font-medium text-center">
                      <span className="text-primary">Click to upload</span> logo
                    </p>
                  </div>
                </div>
                {settings.logo && (
                  <div className="mb-3">
                   <img
                      src={settings.logo}
                      alt="Current Logo"
                      width={100}
                      height={40}
                      className="object-contain border rounded"
                    />
                  </div>
                )}
              </div>
            </div>

            {/* Footer Logo */}
            <div>
              <label className="mb-2.5 block text-sm font-medium text-dark dark:text-white">
                Footer Logo
              </label>
              <div className="relative">                
                <div className="relative block w-full rounded-xl border border-dashed border-gray-4 bg-gray-2 hover:border-primary dark:border-dark-3 dark:bg-dark-2 dark:hover:border-primary">
                  <input
                    type="file"
                    name="footerLogo"
                    accept="image/*"
                    onChange={(e) => handleImageChange('footerLogo', e.target.files?.[0] || null)}
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                  />
                  <div className="flex cursor-pointer flex-col items-center justify-center p-4">
                    <div className="flex size-10 items-center justify-center rounded-full border border-stroke bg-white dark:border-dark-3 dark:bg-gray-dark">
                      <UploadIcon />
                    </div>
                    <p className="mt-2 text-xs font-medium text-center">
                      <span className="text-primary">Click to upload</span> footer logo
                    </p>
                  </div>
                </div>
                {settings.footerLogo && (
                  <div className="mb-3">
                    <img
                      src={settings?.footerLogo}
                      alt="Current Footer Logo"
                      width={100}
                      height={40}
                      className="object-contain border rounded"
                    />
                  </div>
                )}
              </div>
            </div>

            {/* Favicon */}
            <div>
              <label className="mb-2.5 block text-sm font-medium text-dark dark:text-white">
                Favicon
              </label>
              <div className="relative">                
                <div className="relative block w-full rounded-xl border border-dashed border-gray-4 bg-gray-2 hover:border-primary dark:border-dark-3 dark:bg-dark-2 dark:hover:border-primary">
                  <input
                    type="file"
                    name="favicon"
                    accept="image/*"
                    onChange={(e) => handleImageChange('favicon', e.target.files?.[0] || null)}
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                  />
                  <div className="flex cursor-pointer flex-col items-center justify-center p-4">
                    <div className="flex size-10 items-center justify-center rounded-full border border-stroke bg-white dark:border-dark-3 dark:bg-gray-dark">
                      <UploadIcon />
                    </div>
                    <p className="mt-2 text-xs font-medium text-center">
                      <span className="text-primary">Click to upload</span> favicon
                    </p>
                  </div>
                </div>
                {settings.favicon && (
                  <div className="mb-3">
                    <img
                      src={settings?.favicon}
                      alt="Current Favicon"
                      width={32}
                      height={32}
                      className="object-contain border rounded"
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Settings */}
        {/* <div className="mb-5.5">
          <h3 className="mb-4 text-lg font-semibold text-dark dark:text-white">Settings</h3>

          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              name="isActive"
              id="isActive"
              defaultChecked={settings.isActive}
              className="w-4 h-4 text-primary bg-gray-100 border-gray-300 rounded focus:ring-primary dark:focus:ring-primary dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
            />
            <label htmlFor="isActive" className="text-sm font-medium text-dark dark:text-white">
              Active Settings
            </label>
          </div>
        </div> */}

        {/* Submit Buttons */}
        <div className="flex justify-end gap-3">
          {/* <button
            type="button"
            onClick={fetchSettings}
            className="flex justify-center rounded-lg border border-stroke px-6 py-[7px] font-medium text-dark hover:shadow-1 dark:border-dark-3 dark:text-white"
            disabled={saving}
          >
            Reset
          </button> */}
          <button
            type="submit"
            className="flex items-center justify-center rounded-lg bg-primary px-6 py-[7px] font-medium text-gray-2 hover:bg-opacity-90 disabled:opacity-50"
            disabled={saving}
          >
            {saving ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                Saving...
              </>
            ) : (
              'Save Settings'
            )}
          </button>
        </div>
      </form>
    </ShowcaseSection>
  );
}