// src/private/furniture/AddOrEditFurnitureVariantForm.jsx
import { useEffect, useMemo, useState } from 'react';
import { Box, Button, TextField, MenuItem, Grid, CircularProgress } from '@mui/material';
import FurnitureVariantApi from '../../../api/ProductsApi';
import CategoriesApi from '../../../api/CategoriesApi';
import TagTypeApi from '../../../api/TagTypeApi';
import { useAuth } from '../../../context/AuthContext';

const DEFAULT_MODEL_ID = '8a23117b-acaf-4d87-b64f-a98e9b414796';

const TYPE_NAMES = {
  category: 'Furniture category',
  provider: 'Provider',
  color: 'Color',
  line: 'Line',
  currency: 'Currency',
  material: 'Material',
  legs: 'Legs',
  origin: 'Origin',
};

export default function AddOrEditProductCollectionForm({ initialData, onAdd, onCancel }) {
  const { user } = useAuth();
  const token = user?.thalosToken || localStorage.getItem('thalosToken');

  const variantApi = useMemo(() => new FurnitureVariantApi(token), [token]);
  const tagTypeApi = useMemo(() => new TagTypeApi(token), [token]);
  const categoriesApi = useMemo(() => new CategoriesApi(token), [token]);

  const [loadingTags, setLoadingTags] = useState(true);
  const [typeMap, setTypeMap] = useState({});
  const [options, setOptions] = useState({
    categories: [],
    providers: [],
    colors: [],
    lines: [],
    currencies: [],
    materials: [],
    legs: [],
    origins: [],
  });

  const [form, setForm] = useState({
    _Id: '',
    id: '',
    modelId: DEFAULT_MODEL_ID,
    name: '',
    color: '',
    line: '',
    stock: 0,
    price: 0,
    currency: 'USD',
    categoryId: '',
    providerId: '',
    attributes: { material: '', legs: '', origin: '' },
    status: 'Active',
  });

  const setVal = (path, value) => {
    if (path.startsWith('attributes.')) {
      const k = path.split('.')[1];
      setForm(prev => ({ ...prev, attributes: { ...prev.attributes, [k]: value } }));
    } else {
      setForm(prev => ({ ...prev, [path]: value }));
    }
  };

  const parsePrice = (p) => {
    if (p == null) return 0;
    if (typeof p === 'number') return p;
    if (typeof p === 'string') return Number(p) || 0;
    if (typeof p === 'object' && p.$numberDecimal) return Number(p.$numberDecimal) || 0;
    return 0;
  };

  // Cargar TagTypes + Tags
  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const [types, tags] = await Promise.all([tagTypeApi.getAll(), categoriesApi.getAll()]);

        const tmap = {};
        types?.forEach(t => {
          if (!t?.typeName || !t?._id) return;
          tmap[t.typeName] = t._id;
        });

        const byType = (tname) => {
          const tid = tmap[tname];
          if (!tid) return [];
          return (tags || [])
            .filter(tag => tag?.typeId === tid)
            .map(tag => ({ ...tag }));
        };

        if (mounted) {
          setTypeMap(tmap);
          setOptions({
            categories: byType(TYPE_NAMES.category),
            providers: byType(TYPE_NAMES.provider),
            colors: byType(TYPE_NAMES.color),
            lines: byType(TYPE_NAMES.line),
            currencies: byType(TYPE_NAMES.currency),
            materials: byType(TYPE_NAMES.material),
            legs: byType(TYPE_NAMES.legs),
            origins: byType(TYPE_NAMES.origin),
          });
        }
      } catch (err) {
        console.error('Failed loading TagTypes/Tags', err);
      } finally {
        if (mounted) setLoadingTags(false);
      }
    })();
    return () => { mounted = false; };
  }, [tagTypeApi, categoriesApi]);

  // Sembrar datos al editar
  useEffect(() => {
    if (!initialData) return;
    setForm({
      _Id: initialData._Id ?? initialData._id ?? '',
      id: initialData.id ?? '',
      modelId: initialData.modelId ?? DEFAULT_MODEL_ID,
      name: initialData.name ?? '',
      color: initialData.color ?? '',
      line: initialData.line ?? '',
      stock: Number(initialData.stock ?? 0),
      price: parsePrice(initialData.price),
      currency: initialData.currency ?? 'USD',
      categoryId: initialData.categoryId ?? '',
      providerId: initialData.providerId ?? '',
      attributes: {
        material: initialData?.attributes?.material ?? '',
        legs: initialData?.attributes?.legs ?? '',
        origin: initialData?.attributes?.origin ?? '',
      },
      status: initialData.status ?? 'Active',
    });
  }, [initialData]);

  // Si viene GUID/_id/slug => convertir a tagName
  useEffect(() => {
    if (loadingTags) return;

    const toTagNameIfNeeded = (value, list) => {
      if (!value) return '';
      if (list.some(t => t.tagName === value)) return value; // ya es tagName
      const found = list.find(t => t.id === value || t._id === value || t._id?.$oid === value || t.slug === value);
      return found?.tagName || value;
    };

    setForm(prev => ({
      ...prev,
      categoryId: toTagNameIfNeeded(prev.categoryId, options.categories),
      providerId: toTagNameIfNeeded(prev.providerId, options.providers),
      color: toTagNameIfNeeded(prev.color, options.colors),
      line: toTagNameIfNeeded(prev.line, options.lines),
      currency: toTagNameIfNeeded(prev.currency, options.currencies),
      attributes: {
        ...prev.attributes,
        material: toTagNameIfNeeded(prev.attributes?.material, options.materials),
        legs: toTagNameIfNeeded(prev.attributes?.legs, options.legs),
        origin: toTagNameIfNeeded(prev.attributes?.origin, options.origins),
      }
    }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadingTags, options]);

  const handleSubmit = async () => {
    try {
      const payload = {
        ...form,
        stock: Number(form.stock ?? 0),
        price: Number(form.price ?? 0),
        categoryId: form.categoryId || null,  // enviamos tagName
        providerId: form.providerId || null,  // enviamos tagName
        attributes: {
          material: form.attributes.material || '',
          legs: form.attributes.legs || '',
          origin: form.attributes.origin || '',
        }
      };

      const isUpdate = Boolean(form.id || form._Id);
      const saved = isUpdate
        ? await variantApi.updateVariant(payload)
        : await variantApi.createVariant(payload);

      onAdd?.(saved);
    } catch (err) {
      console.error(err);
      alert(err?.message || 'Error saving variant');
    }
  };

  return (
    <Box>
      <Grid container spacing={2}>
        <Grid item xs={12} md={6}>
          <TextField label="Model Id" fullWidth value={form.modelId} onChange={(e) => setVal('modelId', e.target.value)} />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField label="Name" fullWidth value={form.name} onChange={(e) => setVal('name', e.target.value)} />
        </Grid>

        {/* Clasificación */}
        <Grid item xs={12} md={6}>
          <TextField
            select
            label="Category"
            fullWidth
            value={form.categoryId}
            onChange={(e) => setVal('categoryId', e.target.value)}
            helperText="Se envía el tagName por ahora"
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.categories.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        <Grid item xs={12} md={6}>
          <TextField
            select
            label="Provider"
            fullWidth
            value={form.providerId}
            onChange={(e) => setVal('providerId', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.providers.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        {/* Específicos de variante */}
        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Color"
            fullWidth
            value={form.color}
            onChange={(e) => setVal('color', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.colors.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Line"
            fullWidth
            value={form.line}
            onChange={(e) => setVal('line', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.lines.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Currency"
            fullWidth
            value={form.currency}
            onChange={(e) => setVal('currency', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.currencies.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        {/* Atributos como catálogos */}
        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Material"
            fullWidth
            value={form.attributes.material}
            onChange={(e) => setVal('attributes.material', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.materials.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Legs"
            fullWidth
            value={form.attributes.legs}
            onChange={(e) => setVal('attributes.legs', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.legs.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        <Grid item xs={12} md={4}>
          <TextField
            select
            label="Origin"
            fullWidth
            value={form.attributes.origin}
            onChange={(e) => setVal('attributes.origin', e.target.value)}
          >
            {loadingTags && <MenuItem value="" disabled><CircularProgress size={16} /> Cargando…</MenuItem>}
            {!loadingTags && options.origins.filter(t => t.status !== 'Inactive').map(tag => (
              <MenuItem key={tag._id?.$oid || tag._id || tag.id} value={tag.tagName}>{tag.tagName}</MenuItem>
            ))}
          </TextField>
        </Grid>

        {/* Números */}
        <Grid item xs={12} md={4}>
          <TextField label="Stock" type="number" fullWidth value={form.stock} onChange={(e) => setVal('stock', e.target.value)} />
        </Grid>
        <Grid item xs={12} md={4}>
          <TextField label="Price" type="number" fullWidth value={form.price} onChange={(e) => setVal('price', e.target.value)} />
        </Grid>

        {/* Status */}
        <Grid item xs={12} md={4}>
          <TextField select label="Status" fullWidth value={form.status} onChange={(e) => setVal('status', e.target.value)}>
            <MenuItem value="Active">Active</MenuItem>
            <MenuItem value="Inactive">Inactive</MenuItem>
          </TextField>
        </Grid>
      </Grid>

      <Box display="flex" justifyContent="flex-end" mt={3} gap={1}>
        <Button onClick={onCancel} className="button-transparent">Cancel</Button>
        <Button variant="contained" onClick={handleSubmit} className="button-gold">Save</Button>
      </Box>
    </Box>
  );
}
