import { useState } from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import Select from "react-select";
import Swal from 'sweetalert2';

import Offcanvas from "../../components/Offcanvas";
import ImageUpload from "../../components/ImageUpload";
import MultiImageUpload from "../../components/MultiImageUpload";
import Button from "../../components/Buttons";
import TouchSpin from "../../components/TouchSpin";

type ProductType = "single" | "variable";
type AddProductPanelProps = {
  open: boolean;
  setOpen: (v: boolean) => void;
  mode: "add" | "edit" | "view";
  editData?: any; // replace with Product type later
};
type Variant = {
  color: string;
  regularPrice: number;
  salePrice: number;
  stock: number;
};

type FormValues = {
  title: string;
  sku: string;
  category: string;
  brand: string;
  tag: string;
  type: ProductType;
  channels: string[];
  channelStock: {
    instagram: 0,
    web: 0,
    whatsapp: 0,
  },
  thumbnail: string | null;
  gallery: string[];
  regularPrice?: number;
  salePrice?: number;
  stock?: number;
  low_stock?: number;
  variants: Variant[];
  description?: string;
};

type ChannelKey = "instagram" | "web" | "whatsapp";

const salesChannels: {
  key: ChannelKey;
  color: string;
  label: string;
}[] = [
    { key: "instagram", color: "pink", label: "Instagram" },
    { key: "web", color: "blue", label: "Web" },
    { key: "whatsapp", color: "green", label: "WhatsApp" },
  ];

const validationSchema = Yup.object({
  title: Yup.string().required("Product name is required"),
  sku: Yup.string().required("SKU is required"),
  category: Yup.string().required("Category is required"),
  brand: Yup.string().required("Brand is required"),
  tag: Yup.string().required("Tag is required"),
  type: Yup.string().required("Product type is required"),
});

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 selectStyles = {
  control: (base: any, state: any) => ({
    ...base,
    transition: "all 0.2s ease",
    backgroundColor: "#FBF6ED",
    borderColor: state.isFocused ? "#CF8F42" : "#ECE2D2",
    boxShadow: state.isFocused
      ? "0 0 0 3px rgba(207, 143, 66, 0.15)"
      : "none",
    borderRadius: "10px",
    padding: "2px 6px",
    minHeight: "42px",
    fontSize: "14px",
    color: "#3B2F28",
    "&:hover": {
      borderColor: "#CF8F42",
    },
  }),

  valueContainer: (base: any) => ({
    ...base,
    padding: "2px 6px",
  }),

  input: (base: any) => ({
    ...base,
    color: "#3B2F28",
  }),

  placeholder: (base: any) => ({
    ...base,
    color: "#9A8F86",
    fontSize: "14px",
  }),

  singleValue: (base: any) => ({
    ...base,
    color: "#3B2F28",
    fontSize: "14px",
  }),

  menu: (base: any) => ({
    ...base,
    borderRadius: "10px",
    overflow: "hidden",
    marginTop: 6,
    backgroundColor: "#ffffff",
    border: "1px solid #ECE2D2",
  }),

  option: (base: any, state: any) => ({
    ...base,
    fontSize: "14px",
    backgroundColor: state.isFocused
      ? "#FBF6ED"
      : state.isSelected
        ? "#F3E3C7"
        : "#fff",
    color: "#3B2F28",
    cursor: "pointer",
  }),

  dropdownIndicator: (base: any) => ({
    ...base,
    color: "#3B2F28",
    "&:hover": {
      color: "#CF8F42",
    },
  }),

  indicatorSeparator: () => ({
    display: "none",
  }),
};

const categoryOptions = [
  { label: "Necklaces", value: "necklaces" },
  { label: "Rings", value: "rings" },
];

const brandOptions = [
  { label: "Gold Brand", value: "gold" },
  { label: "Silver Brand", value: "silver" },
];

const tagOptions = [
  { label: "New", value: "new" },
  { label: "Trending", value: "trending" },
];

const typeOptions = [
  { label: "Single", value: "single" },
  { label: "Variable", value: "variable" },
];

export default function AddProductPanel({
  open,
  setOpen,
  mode,
  editData,
}: AddProductPanelProps) {
  const [thumbnail, setThumbnail] = useState<string | null>(null);
  const [gallery, setGallery] = useState<string[]>([]);
  const [colorInput, setColorInput] = useState("");
  const channelStock = {
    instagram: editData?.stock?.instagram ?? 0,
    web: editData?.stock?.web ?? 0,
    whatsapp: editData?.stock?.whatsapp ?? 0,
  };


  const getInitialValues = (editData?: any): FormValues => ({
    title: editData?.name || "",
    sku: editData?.sku || "",
    category: editData?.category || "",
    brand: editData?.brand || "",
    tag: editData?.tag || "",
    type: editData?.type || "single",
    channels: Object.entries(editData?.stock || {})
      .filter(([_, value]) => Number(value) > 0)
      .map(([key]) => key),
    channelStock: {
      instagram: editData?.stock?.instagram ?? 0,
      web: editData?.stock?.web ?? 0,
      whatsapp: editData?.stock?.whatsapp ?? 0,
    },
    thumbnail: editData?.thumbnail || null,
    gallery: editData?.gallery || [],
    regularPrice: editData?.regularPrice,
    salePrice: editData?.salePrice,
    low_stock: editData?.low_stock,
    variants: editData?.variants || [],
    description: editData?.description || "",
  });

  const addColor = (values: FormValues, setFieldValue: any) => {
    if (!colorInput.trim()) return;

    const exists = values.variants.find(v => v.color === colorInput);
    if (exists) return;

    setFieldValue("variants", [
      ...values.variants,
      { color: colorInput, regularPrice: 0, salePrice: 0, stock: 0 }
    ]);

    setColorInput("");
  };

  return (
    <Offcanvas
      isOpen={open}
      onClose={() => setOpen(false)}
      header={
        <div className="flex justify-between items-center">
          <h2 className="font-semibold text-lg text-[#7a2e1d]">
            {mode === "edit" ? "Edit Product" : "Add Product"}
          </h2>
          <button onClick={() => setOpen(false)}>✕</button>
        </div>
      }
      footer={
        <div className="border-t p-4 flex justify-end gap-3 bg-white shrink-0">
          <Button
            type="button"
            onClick={() => setOpen(false)}
            children="Cancel"
            variant="secondary"
            styleType="outlined"
          />

          <Button
            type="submit"
            children={mode === "edit" ? "Update Product" : "Save Product"}
            variant="primary"
            styleType="filled"
          />
        </div>
      }
    >
      <Formik
        initialValues={getInitialValues(editData)}
        enableReinitialize
        validationSchema={validationSchema}
        onSubmit={(values) => {
          const toast: any = Swal.mixin({
            toast: true,
            position: 'top',
            showConfirmButton: false,
            timer: 3000,
            customClass: { container: 'toast' },
          });

          if (mode === "edit") {
            console.log("UPDATE PRODUCT", values);
            toast.fire({ icon: 'success', title: 'Product updated successfully.', padding: '10px 20px' });
          } else {
            console.log("CREATE PRODUCT", values);
            toast.fire({ icon: 'success', title: 'Product created successfully.', padding: '10px 20px' });
          }

          setOpen(false);
        }}
      >
        {({ values, setFieldValue }) => (
          <Form className="flex flex-col h-full min-h-0">

            <div className="flex-1 min-h-0 overflow-y-auto p-4 space-y-6">

              <section className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium">Product Name *</label>
                  <Field name="title" className={inputCls} />
                  <ErrorMessage name="title" component="p" className="text-red-500 text-xs" />
                </div>
                <div>
                  <label className="text-sm font-medium">SKU Code *</label>
                  <Field name="sku" className={inputCls} />
                </div>
                <div>
                  <label className="text-sm font-medium">Category *</label>
                  <Field name="category">
                    {({ field, form }: any) => (
                      <Select
                        options={categoryOptions}
                        styles={selectStyles}
                        value={categoryOptions.find(o => o.value === field.value)}
                        onChange={(val: any) =>
                          form.setFieldValue("category", val?.value)
                        }
                      />
                    )}
                  </Field>
                </div>
                <div>
                  <label className="text-sm font-medium">Brand *</label>
                  <Field name="brand">
                    {({ field, form }: any) => (
                      <Select
                        options={brandOptions}
                        styles={selectStyles}
                        value={brandOptions.find(o => o.value === field.value)}
                        onChange={(val: any) =>
                          form.setFieldValue("brand", val?.value)
                        }
                      />
                    )}
                  </Field>
                </div>
                <div>
                  <label className="text-sm font-medium">Tag *</label>
                  <Field name="tag">
                    {({ field, form }: any) => (
                      <Select
                        options={tagOptions}
                        styles={selectStyles}
                        value={tagOptions.find(o => o.value === field.value)}
                        onChange={(val: any) =>
                          form.setFieldValue("tag", val?.value)
                        }
                      />
                    )}
                  </Field>
                </div>
                <div>
                  <label className="text-sm font-medium">Product Type *</label>
                  <Field name="type">
                    {({ field, form }: any) => (
                      <Select
                        options={typeOptions}
                        styles={selectStyles}
                        value={typeOptions.find(o => o.value === field.value)}
                        onChange={(val: any) =>
                          form.setFieldValue("type", val?.value)
                        }
                      />
                    )}
                  </Field>
                </div>
              </section>
              <section>
                <label className="text-sm font-semibold">Sales Channels</label>
                <div className="space-y-3 mt-3">
                  {[
                    { key: "instagram", color: "pink", label: "Instagram" },
                    { key: "web", color: "blue", label: "Web" },
                    { key: "whatsapp", color: "green", label: "WhatsApp" },
                  ].map((ch) => {
                    const active = values.channels.includes(ch.key);

                    const colorMap: any = {
                      pink: {
                        active: "border-pink-400 bg-pink-50 text-pink-700",
                        dot: "bg-pink-500",
                      },
                      blue: {
                        active: "border-blue-400 bg-blue-50 text-blue-700",
                        dot: "bg-blue-500",
                      },
                      green: {
                        active: "border-green-400 bg-green-50 text-green-700",
                        dot: "bg-green-500",
                      },
                    };

                    return (
                      <div
                        key={ch.key}
                        className={`rounded-lg border p-3 transition ${active
                          ? colorMap[ch.color].active
                          : "border-slate-200 bg-white"
                          }`}
                      >
                        <div className="flex items-center justify-between">
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={active}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setFieldValue("channels", [
                                    ...values.channels,
                                    ch.key,
                                  ]);
                                } else {
                                  setFieldValue(
                                    "channels",
                                    values.channels.filter((c) => c !== ch.key)
                                  );
                                }
                              }}
                              className="hidden"
                            />
                            <span
                              className={`w-4 h-4 rounded border flex items-center justify-center ${active
                                ? colorMap[ch.color].dot
                                : "border-slate-300"
                                }`}
                            >
                              {active && (
                                <span className="w-2 h-2 bg-white rounded-full" />
                              )}
                            </span>

                            <span className="text-sm font-medium">{ch.label}</span>
                          </label>

                          {active && (
                            <TouchSpin
                              value={values.channelStock[ch.key as keyof typeof values.channelStock]}
                              onChange={(value) =>
                                setFieldValue(`channelStock.${ch.key}`, value)
                              }
                              min={0}
                            />
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </section>

              {/* ================= MEDIA ================= */}
              <section className="grid grid-cols-1 md:grid-cols-1 gap-4">
                <ImageUpload label="Thumbnail Image" value={thumbnail} onChange={setThumbnail} />
                <MultiImageUpload images={gallery} setImages={setGallery} />
              </section>

              {/* ================= CONDITIONAL ================= */}
              {values.type === "single" ? (
                <section className="grid grid-cols-2 md:grid-cols-2 gap-4">
                  <div>
                    <label>Regular Price *</label>
                    <Field name="regularPrice" className={inputCls} />
                  </div>

                  <div>
                    <label>Sale Price</label>
                    <Field name="salePrice" className={inputCls} />
                  </div>

                  <div>
                    <label>Stock *</label>
                    <Field name="stock" className={inputCls} />
                  </div>
                  <div>
                    <label>Low Stock *</label>
                    <Field name="low_stock" className={inputCls} />
                  </div>
                </section>
              ) : (
                <section className="space-y-4 border rounded p-4">
                  <label className="font-semibold">Variable Products</label>

                  {/* ADD COLOR */}
                  <div className="flex gap-2 items-end">
                    <div className="flex flex-col">
                      <label>Variant Color *</label>
                      <input
                        value={colorInput}
                        onChange={(e) => setColorInput(e.target.value)}
                        placeholder="Enter color (e.g. Red)"
                        className={inputCls}
                      />
                    </div>
                    <div>
                      <button
                        type="button"
                        onClick={() => addColor(values, setFieldValue)}
                        className="px-3 py-2 bg-black text-white rounded"
                      >
                        Add
                      </button>
                    </div>
                  </div>

                  {/* VARIANTS */}
                  <div className="space-y-3">
                    {values.variants.map((v, i) => (
                      <div key={i} className="grid grid-cols-1 md:grid-cols-1 gap-2 items-center border-b pb-2">
                        <div className="font-medium">{v.color}</div>
                        <div key={i} className="grid grid-cols-4 md:grid-cols-2 gap-2 items-center border p-2 rounded">
                          <div className="flex flex-col">
                            <label>Stock </label>
                            <input
                              placeholder="Stock"
                              className={inputCls}
                            />
                          </div>
                          <div className="flex flex-col">
                            <label>Low Stock</label>
                            <input
                              placeholder="Low Stock"
                              className={inputCls}
                            />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </section>
              )}

              <section>
                <label>Description</label>
                <Field as="textarea" name="description" className={inputCls} />
              </section>

            </div>


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