import { useEffect, useState } from 'react';
import ImageUpload from '../../components/ImageUpload';
import Button from '../../components/Buttons';
import Toast from '../../components/Toast';
import shasLogo from "../../assets/images/shas-Logo.png";
import favIcon from "../../assets/images/Shas_fav_icon.png";
import { settingsApi } from '../../api/settingsApi';
import { BACKEND_URL } from '../../api/axiosInstance';

import * as Yup from 'yup';
import { Formik, Form, Field as FormikField, ErrorMessage } from 'formik';

const inputCls =
  'w-full border border-[#ECE2D2] bg-[#FBF6ED] rounded-[10px] px-[14px] py-[10px] text-[14px] text-[#3B2F28] outline-none box-border focus:border-[#CF8F42] focus:ring-1 focus:ring-[#CF8F42] transition';

const Section = ({ title, children }: any) => (
  <div className="rounded-lg border border-slate-100 bg-white p-4">
    <h2 className="mb-5 text-base font-semibold">{title}</h2>
    {children}
  </div>
);

const Grid = ({ children }: any) => (
  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3">
    {children}
  </div>
);

// ✅ VALIDATION
const validationSchema = Yup.object({
  businessName: Yup.string().nullable(),
  phone: Yup.string()
    .nullable()
    .test('is-mobile', 'Mobile number must be 10 digits', (value) => !value || /^\d{10}$/.test(value.replace(/\D/g, ''))),
  alternatePhone: Yup.string()
    .nullable()
    .test('is-alt-mobile', 'Mobile number must be 10 digits', (value) => !value || /^\d{10}$/.test(value.replace(/\D/g, ''))),
  email: Yup.string()
    .nullable()
    .test('is-email', 'Invalid email', (value) => !value || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)),
  website: Yup.string()
    .nullable()
    .test('is-url', 'Invalid URL', (value) => !value || /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/.test(value)),
  pincode: Yup.string()
    .nullable()
    .test('is-pincode', 'Pincode must be 6 digits', (value) => !value || /^\d{6}$/.test(value)),

  gst: Yup.string().nullable(),
  pan: Yup.string().nullable(),

  bankName: Yup.string().nullable(),
  branchName: Yup.string().nullable(),
  accountHolder: Yup.string().nullable(),
  accountNumber: Yup.string().nullable(),
  ifsc: Yup.string().nullable(),
});

const GeneralSettings = () => {
  const [logo, setLogo] = useState<string | null>(shasLogo);
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoRemoved, setLogoRemoved] = useState(false);

  const [favicon, setFavicon] = useState<string | null>(favIcon);
  const [faviconFile, setFaviconFile] = useState<File | null>(null);
  const [faviconRemoved, setFaviconRemoved] = useState(false);

  const [loading, setLoading] = useState(true);

  const [toast, setToast] = useState<{
    show: boolean;
    message: string;
    type: 'success' | 'error' | 'info';
  }>({
    show: false,
    message: '',
    type: 'success',
  });

  const [initialValues, setInitialValues] = useState({
    businessName: '',
    phone: '',
    alternatePhone: '',
    email: '',
    website: '',
    address: '',
    addressLine2: '',
    addressLine3: '',
    landmark: '',
    city: '',
    state: '',
    pincode: '',

    gst: '',
    pan: '',

    bankName: '',
    branchName: '',
    accountHolder: '',
    accountNumber: '',
    ifsc: '',

    facebook: '',
    instagram: '',
    twitter: '',
    linkedin: '',
    youtube: '',
    github: '',
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const res = await settingsApi.getSettings();
        if (res.success && res.data) {
          const settings = res.data;
          
          const updatedValues = { ...initialValues };
          Object.keys(initialValues).forEach((key) => {
            if (settings[key] !== undefined) {
              updatedValues[key as keyof typeof initialValues] = settings[key] || '';
            }
          });
          setInitialValues(updatedValues);

          if (settings.logo) {
            setLogo(settings.logo);
          }
          if (settings.favicon) {
            setFavicon(settings.favicon);
          }
        }
      } catch (err) {
        console.error('Failed to load settings:', err);
        setToast({
          show: true,
          message: 'Failed to load settings.',
          type: 'error',
        });
      } finally {
        setLoading(false);
      }
    };
    loadSettings();
  }, []);

  const handleLogoChange = (url: string | null, file?: File | null) => {
    setLogo(url);
    if (file) {
      setLogoFile(file);
      setLogoRemoved(false);
    } else if (url === null) {
      setLogoFile(null);
      setLogoRemoved(true);
    }
  };

  const handleFaviconChange = (url: string | null, file?: File | null) => {
    setFavicon(url);
    if (file) {
      setFaviconFile(file);
      setFaviconRemoved(false);
    } else if (url === null) {
      setFaviconFile(null);
      setFaviconRemoved(true);
    }
  };

  const getLogoUrl = () => {
    if (!logo) return null;
    if (logo.startsWith('blob:') || logo.startsWith('data:') || logo.startsWith('http')) return logo;
    return `${BACKEND_URL}${logo}`;
  };

  const getFaviconUrl = () => {
    if (!favicon) return null;
    if (favicon.startsWith('blob:') || favicon.startsWith('data:') || favicon.startsWith('http')) return favicon;
    return `${BACKEND_URL}${favicon}`;
  };

  const handleSubmit = async (values: any) => {
    try {
      const formData = new FormData();
      Object.keys(values).forEach((key) => {
        formData.append(key, values[key] || '');
      });

      if (logoFile) {
        formData.append('logo', logoFile);
      } else if (logoRemoved) {
        formData.append('logo_removed', 'true');
      }

      if (faviconFile) {
        formData.append('favicon', faviconFile);
      } else if (faviconRemoved) {
        formData.append('favicon_removed', 'true');
      }

      const res = await settingsApi.updateSettings(formData);
      if (res.success) {
        setToast({
          show: true,
          message: 'Settings saved successfully!',
          type: 'success',
        });
        window.dispatchEvent(new Event('settings-updated'));
      }
    } catch (err) {
      console.error('Failed to save settings:', err);
      setToast({
        show: true,
        message: 'Failed to save settings.',
        type: 'error',
      });
    }
  };

  if (loading) {
    return (
      <div className="flex h-40 items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-amber-500 border-t-transparent"></div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* ✅ TOAST */}
      <Toast
        show={toast.show}
        message={toast.message}
        type={toast.type}
        onClose={() => setToast({ ...toast, show: false })}
      />

      <Formik
        enableReinitialize
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        <Form className="space-y-3">

          {/* BUSINESS / DEFAULT SHIPMENT SENDER */}
          <Section title="Business & Default Shipment From Address">
            <p className="mb-4 text-xs text-slate-500">
              These details are used as the sender/From address for every India Post article and shipping label.
            </p>
            <Grid>
              {[
                { name: 'businessName', label: 'Business Name' },
                { name: 'phone', label: 'Primary Mobile' },
                { name: 'alternatePhone', label: 'Alternate Mobile' },
                { name: 'email', label: 'Email' },
                { name: 'website', label: 'Website' },
                { name: 'address', label: 'Address Line 1' },
                { name: 'addressLine2', label: 'Address Line 2' },
                { name: 'addressLine3', label: 'Address Line 3' },
                { name: 'landmark', label: 'Landmark' },
                { name: 'city', label: 'City' },
                { name: 'state', label: 'State' },
                { name: 'pincode', label: 'Pincode' },
              ].map(({ name, label }) => (
                <div key={name}>
                  <label className="text-sm">{label}</label>
                  <FormikField name={name} className={inputCls} placeholder={`Enter ${label}`} />
                  <ErrorMessage name={name} component="div" className="text-red-500 text-xs" />
                </div>
              ))}
            </Grid>
          </Section>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Section title="Tax Details">
              <div className="grid grid-cols-1 md:grid-cols-1 gap-2">
                <div>
                  <label>GST</label>
                  <FormikField name="gst" className={inputCls} placeholder="Enter GST" />
                  <ErrorMessage name="gst" component="div" className="text-red-500 text-xs" />
                </div>
                <div>
                  <label>PAN</label>
                  <FormikField name="pan" className={inputCls} placeholder="Enter PAN No" />
                  <ErrorMessage name="pan" component="div" className="text-red-500 text-xs" />
                </div>
              </div>
            </Section>
            <Section title="Brand Assets">
              <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
                <ImageUpload
                  label="Logo"
                  hint="200×60 px"
                  value={getLogoUrl()}
                  onChange={handleLogoChange}
                  shape="square"
                  size={100}
                />

                <ImageUpload
                  label="Favicon"
                  hint="32×32 px"
                  value={getFaviconUrl()}
                  onChange={handleFaviconChange}
                  shape="square"
                  size={100}
                />
              </div>
            </Section>

          </div>

          <Section title="Bank Details">
            <Grid>
              {[
                { name: 'bankName', label: 'Bank Name' },
                { name: 'branchName', label: 'Branch Name' },
                { name: 'accountHolder', label: 'Account Holder' },
                { name: 'accountNumber', label: 'Account Number' },
                { name: 'ifsc', label: 'IFSC Code' },
              ].map(({ name, label }) => (
                <div key={name}>
                  <label>{label}</label>
                  <FormikField name={name} className={inputCls} placeholder={`Enter ${label}`} />
                  <ErrorMessage name={name} component="div" className="text-red-500 text-xs" />
                </div>
              ))}
            </Grid>
          </Section>
          <Section title="Social Media">
            <Grid>
              {[
                'facebook',
                'instagram',
                'twitter',
                'linkedin',
                'youtube',
                'github',
              ].map((name) => (
                <div key={name}>
                  <label className="capitalize">{name}</label>
                  <FormikField name={name} className={inputCls} placeholder={`Enter ${name}`} />
                </div>
              ))}
            </Grid>
          </Section>

          <div className="flex md:justify-end justify-start">
            <Button type="submit">
              Save Changes
            </Button>
          </div>

        </Form>
      </Formik>
    </div>
  );
};

export default GeneralSettings;
