'use client';

import { useState, useRef } from 'react';
import { toast } from 'react-hot-toast';
import { Camera, Check, RefreshCw, X, Image as ImageIcon, Sparkles, Hash, Layout, Layers, Package, ChevronDown } from 'lucide-react';
import { inventoryApi } from '@/lib/api';

interface AIOnboardingProps {
  onCancel: () => void;
  onComplete: (itemData: any) => void;
  categories: any[];
  inventory: any[];
}

export default function AIOnboarding({ onCancel, onComplete, categories, inventory }: AIOnboardingProps) {
  const [image, setImage] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [extractedData, setExtractedData] = useState<any>(null);
  const [mode, setMode] = useState<'item' | 'box'>('item');

  // Extract unique item types for suggestions
  const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
  const existingBoxes = Array.from(new Set(inventory.map(i => i.box_label).filter(Boolean))).sort() as string[];
  
  const cameraInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => setImage(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  const processImage = async () => {
    if (!image) return;
    setUploading(true);
    
    try {
      const blob = await (await fetch(image)).blob();
      const formData = new FormData();
      formData.append('file', blob, 'label.jpg');

      const data = await inventoryApi.analyzeLabel(formData, mode);

      if (data.error) {
        toast.error(`AI Error: ${data.error}`);
        setUploading(false); // Force stop loading state
        return;
      }

      setExtractedData(data);
      if (mode === 'box') {
        toast.success(`Box identified: ${data.box_label || data.name}`);
      } else {
        toast.success("AI extraction complete!");
      }
    } catch (error) {
      toast.error("Failed to process image with AI");
      console.error(error);
    } finally {
      setUploading(false);
    }
  };

  const confirmOnboarding = async () => {
    // Sanitize data for the backend (Pydantic validation)
    const newItem = {
      name: String(extractedData.name || "New AI Item"),
      category: String(extractedData.category || "Uncategorized"),
      type: extractedData.type ? String(extractedData.type) : null,
      part_number: extractedData.part_number ? String(extractedData.part_number) : null,
      color: extractedData.color ? String(extractedData.color) : null,
      specs: String(extractedData.specs || ""),
      barcode: String(extractedData.barcode || extractedData.part_number || extractedData.serial_number || `AI-${Date.now()}`),
      quantity: parseFloat(String(extractedData.quantity || 1)),
      min_quantity: 1.0,
      box_label: extractedData.box_label ? String(extractedData.box_label) : null,
      labels_data: JSON.stringify(extractedData)
    };
    onComplete(newItem);
  };

  return (
    <div className="fixed inset-0 z-50 bg-slate-950 flex flex-col p-6 animate-in fade-in slide-in-from-bottom-5 duration-300">
      <div className="flex justify-between items-center mb-6 shrink-0">
        <div className="flex items-center gap-3">
            <div className="p-2 bg-primary/20 rounded-xl">
               <Sparkles className="text-primary w-5 h-5" />
            </div>
            <div>
              <h2 className="text-lg font-bold">AI Discovery</h2>
              <p className="text-xs text-slate-500 font-bold">Powered by Gemini 2.0 Flash</p>
            </div>
        </div>
        <button onClick={onCancel} className="p-2 hover:bg-slate-900 rounded-full transition-colors">
          <X size={24} />
        </button>
      </div>

      {!image ? (
        <div className="flex-1 flex flex-col gap-6 min-h-0">
          <div className="flex bg-slate-900/50 p-1.5 rounded-2xl border border-slate-800/50 shrink-0">
            <button 
              onClick={() => setMode('item')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold transition-all ${mode === 'item' ? 'bg-primary text-white shadow-lg' : 'text-slate-500 hover:text-slate-300'}`}
            >
              <Package size={18} />
              <span className="text-xs">Item Label</span>
            </button>
            <button 
              onClick={() => setMode('box')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold transition-all ${mode === 'box' ? 'bg-primary text-white shadow-lg' : 'text-slate-500 hover:text-slate-300'}`}
            >
              <Layers size={18} />
              <span className="text-xs">Box / Container</span>
            </button>
          </div>

          <div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-800 rounded-[2.5rem] bg-slate-900/30 overflow-hidden px-4">
            <div className="w-20 h-20 bg-slate-900 rounded-3xl flex items-center justify-center mb-6 shadow-inner">
               <Camera size={32} className={mode === 'box' ? 'text-primary' : 'text-slate-500'} />
            </div>
            <p className="text-slate-300 mb-2 text-center font-bold">
              {mode === 'box' ? 'Container Discovery Mode' : 'Label Insight Mode'}
            </p>
            <p className="text-xs text-slate-500 px-8 text-center leading-relaxed font-bold">
              {mode === 'box' 
                ? 'Scan the large, prominent label or hand-written name on the container'
                : 'Scan or upload a sharp photo of the item specifications'}
            </p>
          </div>

          <div className="grid grid-cols-2 gap-4 h-28 shrink-0">
            <button 
              onClick={() => cameraInputRef.current?.click()}
              className="flex flex-col items-center justify-center gap-2 bg-primary text-white rounded-3xl font-bold shadow-2xl shadow-primary/20 active:scale-95 transition-all"
            >
              <Camera size={24} />
              <span className="text-sm">Scan Camera</span>
            </button>
            <button 
              onClick={() => fileInputRef.current?.click()}
              className="flex flex-col items-center justify-center gap-2 bg-slate-900 text-slate-200 border border-slate-800 rounded-3xl font-bold active:scale-95 transition-all"
            >
              <ImageIcon size={24} />
              <span className="text-sm">Upload Photo</span>
            </button>
          </div>

          <input type="file" ref={cameraInputRef} onChange={handleFileChange} accept="image/*" capture="environment" className="hidden" />
          <input type="file" ref={fileInputRef} onChange={handleFileChange} accept="image/*" className="hidden" />
        </div>
      ) : !extractedData ? (
        <div className="flex-1 flex flex-col gap-6 min-h-0 overflow-hidden">
          <div className="relative flex-1 min-h-0 rounded-[2.5rem] overflow-hidden border-4 border-slate-900 shadow-2xl bg-slate-900">
            <img src={image} className="w-full h-full object-contain" alt="Captured label" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent pointer-events-none" />
            
            {uploading && (
              <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm flex flex-col items-center justify-center gap-4 z-10 transition-all">
                <div className="relative">
                  <RefreshCw className="w-12 h-12 text-primary animate-spin" />
                  <Sparkles className="absolute -top-2 -right-2 text-amber-400 w-6 h-6 animate-pulse" />
                </div>
                <p className="text-white font-black tracking-tight text-sm">Gemini is processing...</p>
              </div>
            )}
          </div>

          <div className="flex gap-4 shrink-0 pb-2">
            <button 
              onClick={() => setImage(null)} 
              disabled={uploading}
              className="px-6 py-4 bg-slate-900 border border-slate-800 text-slate-400 rounded-2xl font-bold transition-all active:scale-95 disabled:opacity-50"
            >
              Retake
            </button>
            <button 
              onClick={processImage} 
              disabled={uploading}
              className="flex-1 py-4 bg-primary text-white rounded-2xl font-black text-lg shadow-xl shadow-primary/30 flex items-center justify-center gap-3 active:scale-95 disabled:opacity-50 hover:bg-blue-500"
            >
              {uploading ? "Analyzing..." : "Extract Data"}
              {!uploading && <Check size={20} />}
            </button>
          </div>
        </div>
      ) : (
        <div className="flex-1 flex flex-col gap-6 overflow-hidden">
          <div className="flex items-center justify-between">
              <span className="text-xs text-slate-500 font-bold">Validation Mask</span>
              <span className="text-xs bg-green-500/10 text-green-400 px-2 py-0.5 rounded-full font-bold">AI Ready</span>
          </div>
          
          <div className="flex-1 overflow-y-auto space-y-4 pr-1 scrollbar-hide">
            <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
              <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Item Name</label>
              <textarea 
                value={extractedData.name || ''} 
                onChange={(e) => setExtractedData({...extractedData, name: e.target.value})}
                className="bg-transparent w-full text-xl font-bold outline-none text-white placeholder:text-slate-700 resize-none h-20"
                placeholder="Product name..."
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
               <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <div className="flex items-center gap-1.5 mb-1 ml-1 group-focus-within:text-primary transition-colors">
                  <Layers size={12} />
                  <label className="text-xs text-slate-500 font-bold">Category Group</label>
                </div>
                <div className="relative flex items-center">
                  <select 
                    value={extractedData.category || ''} 
                    onChange={(e) => setExtractedData({...extractedData, category: e.target.value})}
                    className="bg-transparent w-full font-bold outline-none text-slate-200 appearance-none"
                  >
                    <option value="" className="bg-slate-900 font-bold">Other / New</option>
                    {categories.map(c => (
                      <option key={c.id} value={c.name} className="bg-slate-900">{c.name}</option>
                    ))}
                  </select>
                  <ChevronDown size={14} className="absolute right-0 text-slate-500 pointer-events-none" />
                </div>
              </div>
              <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <div className="flex items-center gap-1.5 mb-1 ml-1 group-focus-within:text-primary transition-colors">
                  <Package size={12} />
                  <label className="text-xs text-slate-500 font-bold">Item Type</label>
                </div>
                <input 
                  value={extractedData.type || ''} 
                  list="onboarding-types"
                  onChange={(e) => setExtractedData({...extractedData, type: e.target.value})}
                  className="bg-transparent w-full font-bold outline-none text-slate-200"
                  placeholder="e.g. SFP+"
                />
                <datalist id="onboarding-types">
                  {existingTypes.map(t => <option key={t} value={t} />)}
                </datalist>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Item Color</label>
                <div className="flex items-center gap-2">
                   <div className="w-2 h-2 rounded-full" style={{backgroundColor: extractedData.color || 'transparent'}} />
                   <input 
                    value={extractedData.color || ''} 
                    onChange={(e) => setExtractedData({...extractedData, color: e.target.value})}
                    className="bg-transparent w-full font-bold outline-none text-slate-200"
                    placeholder="e.g. Turquoise"
                  />
                </div>
              </div>
              <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Box / Container Label</label>
                <input 
                  value={extractedData.box_label || ''} 
                  list="onboarding-boxes"
                  onChange={(e) => setExtractedData({...extractedData, box_label: e.target.value})}
                  className="bg-transparent w-full font-bold outline-none text-slate-200"
                  placeholder="e.g. Box 1"
                />
                <datalist id="onboarding-boxes">
                  {existingBoxes.map(b => <option key={b} value={b} />)}
                </datalist>
              </div>
            </div>

            <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
              <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Technical Specifications</label>
              <textarea 
                value={extractedData.specs || ''} 
                onChange={(e) => setExtractedData({...extractedData, specs: e.target.value})}
                className="bg-transparent w-full text-sm leading-relaxed outline-none resize-none h-20 text-slate-300"
                placeholder="Technical details..."
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Part Number (P/N)</label>
                <div className="flex items-center gap-2">
                  <Hash size={14} className="text-primary/60" />
                  <input 
                    value={extractedData.part_number || ''} 
                    onChange={(e) => setExtractedData({...extractedData, part_number: e.target.value})}
                    className="bg-transparent w-full font-mono text-sm outline-none text-slate-200"
                    placeholder="ID code..."
                  />
                </div>
              </div>
              <div className="bg-slate-900/80 p-5 rounded-[1.5rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-1 block group-focus-within:text-primary transition-colors">Initial Stock</label>
                <div className="flex items-center gap-2">
                  <Layout size={14} className="text-amber-500/60" />
                  <input 
                    type="number"
                    value={extractedData.quantity || 1} 
                    onChange={(e) => setExtractedData({...extractedData, quantity: parseInt(e.target.value)})}
                    className="bg-transparent w-full font-black text-lg outline-none text-slate-200"
                  />
                </div>
              </div>
            </div>

            <div className="bg-slate-900/30 p-4 rounded-[1.5rem] border border-slate-800/50">
               <label className="text-xs text-slate-500 font-bold mb-1 block">System Metadata (S/N if found)</label>
               <div className="text-[10px] text-slate-500 font-mono flex flex-wrap gap-2">
                 {extractedData.serial_number && <span>S/N: {extractedData.serial_number}</span>}
                 {extractedData.additional_data && <span>+ More Data</span>}
               </div>
            </div>
          </div>

          <div className="flex flex-col gap-3 shrink-0">
             <button 
              onClick={confirmOnboarding}
              className="py-5 bg-primary text-white rounded-[1.8rem] font-black text-lg shadow-2xl shadow-primary/20 active:scale-95 transition-all hover:bg-blue-500"
            >
              Confirm to Catalog
            </button>
            <button 
              onClick={() => setExtractedData(null)}
              className="py-3 text-xs text-slate-600 font-bold hover:text-slate-400"
            >
              Reset Extraction
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
