'use client';

import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { GripVertical, X, ChevronDown } from 'lucide-react';
import { cn, formatIDR } from '@/lib/utils';
import type { VariantPayload } from '@/lib/services/product.service';
import { Field, DarkInput } from '@/components/ui/form-elements';

export function VariantRow({
  variant,
  index,
  isNew,
  onChange,
  onRemove,
  canRemove,
}: {
  variant: VariantPayload & { _id?: string; _isNew?: boolean };
  index: number;
  isNew?: boolean;
  onChange: (updated: VariantPayload) => void;
  onRemove: () => void;
  canRemove: boolean;
}) {
  const [expanded, setExpanded] = useState(isNew);

  const update = (field: keyof VariantPayload, value: unknown) =>
    onChange({ ...variant, [field]: value });
  const updateAttr = (field: string, value: string) =>
    onChange({
      ...variant,
      attributes: { ...variant.attributes, [field]: value },
    });

  return (
    <div
      className={cn(
        'border rounded-2xl overflow-hidden transition-all duration-300',
        isNew
          ? 'border-yellow-300 bg-yellow-50'
          : expanded
            ? 'border-yellow-300 bg-white'
            : 'border-gray-200 bg-white/40 hover:border-gray-300'
      )}
    >
      <div
        className={cn(
          'flex items-center gap-3 px-5 py-4 cursor-pointer select-none',
          isNew ? 'bg-yellow-50' : 'bg-white/40'
        )}
        onClick={() => setExpanded((v) => !v)}
      >
        <GripVertical className="w-5 h-5 text-gray-600 shrink-0 cursor-grab" />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <p className="text-sm font-bold text-gray-900 truncate">
              {variant.name || `Varian ${index + 1}`}
            </p>
            {isNew && (
              <span className="text-[9px] font-bold bg-yellow-400 text-yellow-900 px-2 py-0.5 rounded-md uppercase tracking-widest shadow-sm">
                Baru
              </span>
            )}
          </div>
          <p className="text-[10px] text-gray-500 font-mono tracking-widest mt-1">
            {variant.sku || '—'}
          </p>
        </div>
        <div className="flex items-center gap-4 shrink-0 pl-2">
          <span className="text-xs font-bold text-yellow-600">
            {variant.price ? formatIDR(Number(variant.price)) : '—'}
          </span>
          {canRemove && (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                onRemove();
              }}
              className="p-1.5 rounded-lg text-gray-500 hover:bg-rose-500/10 hover:text-rose-400 transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          )}
          <div
            className={cn(
              'p-1 transition-transform duration-300',
              expanded && 'rotate-180'
            )}
          >
            <ChevronDown className="w-4 h-4 text-gray-500" />
          </div>
        </div>
      </div>

      <AnimatePresence initial={false}>
        {expanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.3 }}
            className="overflow-hidden border-t border-gray-100"
          >
            <div className="p-5 sm:p-6 grid grid-cols-1 sm:grid-cols-2 gap-5">
              <Field label="Nama Varian" required>
                <DarkInput
                  value={variant.name}
                  onChange={(e) => update('name', e.target.value)}
                  placeholder="Contoh: 250g, 500g, 1kg"
                  maxLength={100}
                />
              </Field>
              <Field
                label="SKU Varian"
                required
                hint="Harus unik di seluruh produk"
              >
                <DarkInput
                  value={variant.sku}
                  onChange={(e) => update('sku', e.target.value.toUpperCase())}
                  placeholder="GRM-V01"
                  maxLength={50}
                />
              </Field>
              <Field label="Harga Jual (Rp)" required>
                <DarkInput
                  type="number"
                  min={0}
                  value={variant.price ?? ''}
                  onChange={(e) =>
                    update(
                      'price',
                      e.target.value === '' ? '' : Number(e.target.value)
                    )
                  }
                  placeholder="0"
                />
              </Field>
              <Field label="Stok" required>
                <DarkInput
                  type="number"
                  min={0}
                  value={variant.stock ?? ''}
                  onChange={(e) =>
                    update(
                      'stock',
                      e.target.value === '' ? '' : Number(e.target.value)
                    )
                  }
                  placeholder="0"
                />
              </Field>
              <Field label="Berat (gram)" hint="Opsional">
                <DarkInput
                  type="number"
                  min={0}
                  value={variant.weight ?? ''}
                  onChange={(e) =>
                    update(
                      'weight',
                      e.target.value ? Number(e.target.value) : undefined
                    )
                  }
                  placeholder="0"
                />
              </Field>
              <Field label="Satuan" hint="Contoh: kg, gram, pcs">
                <DarkInput
                  value={variant.attributes?.unit ?? ''}
                  onChange={(e) => updateAttr('unit', e.target.value)}
                  placeholder="gram"
                />
              </Field>
              <Field label="Harga Distributor (Rp)" hint="Opsional">
                <DarkInput
                  type="number"
                  min={0}
                  value={variant.price_distributor ?? ''}
                  onChange={(e) =>
                    update(
                      'price_distributor',
                      e.target.value ? Number(e.target.value) : undefined
                    )
                  }
                  placeholder="0"
                />
              </Field>
              <div className="sm:col-span-2">
                <Field label="Kemasan" hint="Contoh: plastik, karung, botol">
                  <DarkInput
                    value={variant.attributes?.packaging ?? ''}
                    onChange={(e) => updateAttr('packaging', e.target.value)}
                    placeholder="Plastik Food Grade"
                  />
                </Field>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
