/* eslint-disable */
// Item Tracker — household inventory with AI-powered structuring

const ITEM_CATEGORIES = ["Tools", "Electronics", "Kitchen", "Documents", "Storage", "Other"];
const CATEGORY_TONES = { Tools: "warn", Electronics: "info", Kitchen: "success", Documents: "purple", Storage: "orange", Other: "gray" };

const ItemsScreen = () => {
  const [tab, setTab] = React.useState("items");

  // Items state
  const [items, setItems] = React.useState([]);
  const [search, setSearch] = React.useState("");
  const [showAdd, setShowAdd] = React.useState(false);
  const [aiLoading, setAiLoading] = React.useState(false);
  const [draft, setDraft] = React.useState(null);
  const [textInput, setTextInput] = React.useState("");
  const [loading, setLoading] = React.useState(true);
  const [listening, setListening] = React.useState(false);
  const [imageFile, setImageFile] = React.useState(null);
  const [imagePreview, setImagePreview] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const [editItem, setEditItem] = React.useState(null);

  // Locations state
  const [locations, setLocations] = React.useState([]);
  const [locationsLoading, setLocationsLoading] = React.useState(true);
  const [newLocationName, setNewLocationName] = React.useState("");
  const [newLocationDesc, setNewLocationDesc] = React.useState("");
  const [savingLocation, setSavingLocation] = React.useState(false);

  const recognitionRef = React.useRef(null);
  const fileInputRef = React.useRef(null);

  const db = window._db;
  const userId = firebase.auth().currentUser?.uid;
  const hasSpeech = typeof window !== "undefined" && ("SpeechRecognition" in window || "webkitSpeechRecognition" in window);

  const itemsRef = React.useMemo(() => {
    if (!db) return null;
    return db.collection("shared_items");
  }, [db]);

  const locationsRef = React.useMemo(() => {
    if (!db) return null;
    return db.collection("shared_item_locations");
  }, [db]);

  // Items subscription + migration
  React.useEffect(() => {
    if (!itemsRef) return;
    const runMigration = async () => {
      if (!db || !userId) return;
      try {
        const userDoc = await db.collection('users').doc(userId).get();
        if (userDoc.exists && userDoc.data().itemsMigrated) return;
        const oldRef = db.collection('items').doc(userId).collection('items');
        const oldSnap = await oldRef.get();
        if (!oldSnap.empty) {
          const batch = db.batch();
          const existingSnap = await itemsRef.get();
          const existingIds = new Set(existingSnap.docs.map(d => d.data().originalId).filter(Boolean));
          oldSnap.docs.forEach(doc => {
            if (!existingIds.has(doc.id)) {
              const newDoc = itemsRef.doc();
              batch.set(newDoc, { ...doc.data(), createdBy: userId, originalId: doc.id });
            }
          });
          await batch.commit();
        }
        await db.collection('users').doc(userId).update({ itemsMigrated: true });
      } catch (e) { console.error('Migration failed:', e); }
    };
    runMigration().catch(console.error);
    const unsubscribe = itemsRef.orderBy('createdAt', 'desc').onSnapshot(snap => {
      setItems(snap.docs.map(d => ({ id: d.id, ...d.data() })));
      setLoading(false);
    });
    return () => unsubscribe();
  }, [itemsRef, db, userId]);

  // Locations subscription
  React.useEffect(() => {
    if (!locationsRef) return;
    const unsubscribe = locationsRef.orderBy('name', 'asc').onSnapshot(snap => {
      setLocations(snap.docs.map(d => ({ id: d.id, ...d.data() })));
      setLocationsLoading(false);
    }, () => setLocationsLoading(false));
    return () => unsubscribe();
  }, [locationsRef]);

  const locationNames = locations.map(l => l.name);

  const searchLower = search.toLowerCase();
  const filtered = items.filter(item =>
    !search ||
    item.itemName?.toLowerCase().includes(searchLower) ||
    item.location?.toLowerCase().includes(searchLower) ||
    item.category?.toLowerCase().includes(searchLower)
  );

  const toggleVoice = () => {
    if (listening && recognitionRef.current) {
      recognitionRef.current.stop();
      setListening(false);
      return;
    }
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) return;
    const recognition = new SR();
    recognition.continuous = false;
    recognition.interimResults = false;
    recognition.lang = "en-US";
    recognition.onresult = (e) => {
      const transcript = e.results[0][0].transcript;
      setTextInput(prev => prev ? prev + " " + transcript : transcript);
    };
    recognition.onend = () => setListening(false);
    recognition.onerror = () => setListening(false);
    recognitionRef.current = recognition;
    recognition.start();
    setListening(true);
  };

  const handleImageSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImageFile(file);
    const reader = new FileReader();
    reader.onload = (ev) => setImagePreview(ev.target.result);
    reader.readAsDataURL(file);
  };

  const uploadImage = async () => {
    if (!imageFile) return "";
    const storageRef = firebase.storage().ref();
    const path = `shared_items/${Date.now()}_${imageFile.name}`;
    const snap = await storageRef.child(path).put(imageFile);
    return await snap.ref.getDownloadURL();
  };

  const handleAiStructure = async () => {
    if (!textInput.trim()) return;
    setAiLoading(true);
    try {
      const res = await fetch("https://us-central1-jagdevfamilyhub.cloudfunctions.net/structureItem", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ input: textInput.trim(), uid: userId }),
      });
      const data = await res.json();
      // Match AI location to a defined location if possible
      const aiLocation = data.location || "";
      const matchedLocation = locationNames.find(n => n.toLowerCase() === aiLocation.toLowerCase()) || (locationNames.length > 0 ? "" : aiLocation);
      setDraft({
        itemName: data.itemName || textInput.trim(),
        category: ITEM_CATEGORIES.includes(data.category) ? data.category : "Other",
        location: matchedLocation,
        notes: data.notes || "",
        confidence: data.confidence ?? 0.5,
      });
    } catch (e) {
      setDraft({
        itemName: textInput.trim(),
        category: "Other",
        location: "",
        notes: "",
        confidence: 0,
      });
    }
    setAiLoading(false);
  };

  const saveDraft = async () => {
    if (!draft || !itemsRef) return;
    setUploading(true);
    let imageUrl = "";
    try { if (imageFile) imageUrl = await uploadImage(); } catch (e) { console.error("Image upload failed", e); }
    await itemsRef.add({
      itemName: draft.itemName,
      category: draft.category,
      location: draft.location,
      notes: draft.notes,
      aiConfidence: draft.confidence,
      imageUrl,
      createdBy: userId || null,
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
    });
    setDraft(null);
    setTextInput("");
    setImageFile(null);
    setImagePreview(null);
    setShowAdd(false);
    setUploading(false);
  };

  const deleteItem = async (id) => {
    if (!window.confirm("Are you sure you want to delete this item?")) return;
    if (!itemsRef) return;
    await itemsRef.doc(id).delete();
    setItems(prev => prev.filter(i => i.id !== id));
  };

  const startEditItem = (item) => { setEditItem({ ...item }); };
  const saveEditItem = async () => {
    if (!editItem || !itemsRef) return;
    await itemsRef.doc(editItem.id).update({
      itemName: editItem.itemName,
      category: editItem.category,
      location: editItem.location,
      notes: editItem.notes,
      updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
    });
    setEditItem(null);
  };

  const resetModal = () => { setShowAdd(false); setDraft(null); setTextInput(""); setImageFile(null); setImagePreview(null); };

  // Locations management
  const addLocation = async () => {
    const name = newLocationName.trim();
    if (!name || !locationsRef) return;
    setSavingLocation(true);
    try {
      await locationsRef.add({
        name,
        description: newLocationDesc.trim(),
        createdBy: userId || null,
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setNewLocationName("");
      setNewLocationDesc("");
    } catch (e) {
      console.error("Failed to add location:", e);
      alert("Could not save location. Please try again.");
    } finally {
      setSavingLocation(false);
    }
  };

  const deleteLocation = async (id, name) => {
    const usedBy = items.filter(item => item.location === name);
    if (usedBy.length > 0) {
      alert(`"${name}" is used by ${usedBy.length} item${usedBy.length > 1 ? "s" : ""}. Update or remove those items before deleting this location.`);
      return;
    }
    if (!window.confirm(`Delete location "${name}"?`)) return;
    if (!locationsRef) return;
    try {
      await locationsRef.doc(id).delete();
    } catch (e) {
      console.error("Failed to delete location:", e);
      alert("Could not delete location. Please try again.");
    }
  };

  // Location select options — merges defined locations with any legacy free-text values on existing items
  const LocationSelect = ({ value, onChange }) => {
    const legacyValue = value && !locationNames.includes(value) ? value : null;
    return (
      <Select value={value || ""} onChange={onChange}>
        <option value="">— No location —</option>
        {legacyValue && <option value={legacyValue}>{legacyValue} (custom)</option>}
        {locationNames.map(name => <option key={name} value={name}>{name}</option>)}
      </Select>
    );
  };

  if (loading) return <section className="p-4 md:p-6"><p className="text-gray-500">Loading items...</p></section>;

  return (
    <section className="p-4 md:p-6 space-y-4">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Item Tracker</h2>
      </div>

      {/* Tab navigation */}
      <div className="flex gap-0 border-b border-gray-200 dark:border-gray-700">
        {[{ id: "items", label: "Items" }, { id: "locations", label: "Locations" }].map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
              tab === t.id
                ? "border-blue-500 text-blue-600 dark:text-blue-400"
                : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Items tab */}
      {tab === "items" && (
        <>
          <Input
            placeholder="Search items by name, location, or category..."
            value={search}
            onChange={e => setSearch(e.target.value)}
          />

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {filtered.map(item => (
              <Card key={item.id} className="relative">
                {item.imageUrl && (
                  <img src={item.imageUrl} alt={item.itemName} className="w-full h-40 object-cover rounded-lg mb-3" />
                )}
                <h3 className="font-semibold text-gray-900 dark:text-white text-lg">{item.itemName}</h3>
                {item.location && <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">📍 {item.location}</p>}
                <div className="mt-2">
                  <Pill tone={CATEGORY_TONES[item.category] || "gray"}>{item.category}</Pill>
                </div>
                {item.notes && <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">{item.notes}</p>}
                <div className="flex gap-3 mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
                  <button onClick={() => startEditItem(item)} className="text-blue-500 hover:text-blue-700 text-sm font-medium">Edit</button>
                  <button onClick={() => deleteItem(item.id)} className="text-red-500 hover:text-red-700 text-sm font-medium">Delete</button>
                </div>
              </Card>
            ))}
            {filtered.length === 0 && <p className="text-gray-500 col-span-full text-center py-8">No items found. Add your first item!</p>}
          </div>

          {/* FAB */}
          <button
            onClick={() => setShowAdd(true)}
            className="fixed bottom-6 right-6 w-14 h-14 bg-blue-600 hover:bg-blue-700 text-white rounded-full shadow-lg flex items-center justify-center text-2xl z-30 transition-colors"
          >+</button>
        </>
      )}

      {/* Locations tab */}
      {tab === "locations" && (
        <div className="space-y-6 max-w-lg">
          <div>
            <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-1">Add Location</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">Define the places where items are stored (e.g. Garage, Kitchen pantry, Attic).</p>
            <div className="space-y-2">
              <Input
                placeholder="Location name (e.g. Garage)"
                value={newLocationName}
                onChange={e => setNewLocationName(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter") addLocation(); }}
              />
              <Input
                placeholder="Description (optional)"
                value={newLocationDesc}
                onChange={e => setNewLocationDesc(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter") addLocation(); }}
              />
              <BtnPrimary onClick={addLocation} disabled={savingLocation || !newLocationName.trim()}>
                {savingLocation ? "Adding..." : "Add Location"}
              </BtnPrimary>
            </div>
          </div>

          <div>
            <h3 className="text-base font-semibold text-gray-900 dark:text-white mb-3">
              Saved Locations {locations.length > 0 && <span className="text-sm font-normal text-gray-400">({locations.length})</span>}
            </h3>
            {locationsLoading ? (
              <p className="text-sm text-gray-400">Loading...</p>
            ) : locations.length === 0 ? (
              <p className="text-sm text-gray-400">No locations yet. Add one above.</p>
            ) : (
              <div className="space-y-2">
                {locations.map(loc => (
                  <div key={loc.id} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                    <div>
                      <p className="text-sm font-medium text-gray-900 dark:text-white">📍 {loc.name}</p>
                      {loc.description && <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">{loc.description}</p>}
                    </div>
                    <button
                      onClick={() => deleteLocation(loc.id, loc.name)}
                      className="text-red-400 hover:text-red-600 text-sm font-medium ml-4 shrink-0"
                    >
                      Delete
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Edit Item Modal */}
      {editItem && (
        <Modal title="Edit Item" onClose={() => setEditItem(null)} onSubmit={saveEditItem} submitLabel="Save">
          <div className="space-y-3">
            <div><Label required>Item Name</Label><Input value={editItem.itemName} onChange={e => setEditItem({...editItem, itemName: e.target.value})} autoFocus /></div>
            <div><Label>Category</Label><Select value={editItem.category} onChange={e => setEditItem({...editItem, category: e.target.value})}>{ITEM_CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}</Select></div>
            <div>
              <Label>Location</Label>
              {locationNames.length > 0 ? (
                <LocationSelect value={editItem.location || ""} onChange={e => setEditItem({...editItem, location: e.target.value})} />
              ) : (
                <Input value={editItem.location || ''} onChange={e => setEditItem({...editItem, location: e.target.value})} placeholder="Where is this item?" />
              )}
            </div>
            <div><Label>Notes</Label><Textarea rows={2} value={editItem.notes || ''} onChange={e => setEditItem({...editItem, notes: e.target.value})} /></div>
          </div>
        </Modal>
      )}

      {/* Add Item Modal */}
      {showAdd && (
        <Modal title={draft ? "Confirm Item" : "Add Item"} onClose={resetModal}>
          {!draft ? (
            <div className="space-y-4">
              <div>
                <Label>Describe the item</Label>
                <div className="relative">
                  <Textarea
                    rows={3}
                    placeholder="e.g. Red toolbox in the garage on the top shelf"
                    value={textInput}
                    onChange={e => setTextInput(e.target.value)}
                    onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleAiStructure(); } }}
                  />
                  {hasSpeech && (
                    <button
                      onClick={toggleVoice}
                      className={"absolute bottom-3 right-3 w-9 h-9 rounded-full flex items-center justify-center transition-colors " + (listening ? "bg-red-500 text-white animate-pulse" : "bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500")}
                      title={listening ? "Stop recording" : "Voice input"}
                    >
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
                    </button>
                  )}
                </div>
              </div>

              {/* Image upload */}
              <div>
                <Label>Photo (optional)</Label>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  capture="environment"
                  onChange={handleImageSelect}
                  className="hidden"
                />
                <div className="flex items-center gap-3">
                  <BtnSecondary onClick={() => fileInputRef.current?.click()}>
                    <span className="flex items-center gap-2">
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/><circle cx="12" cy="13" r="3"/></svg>
                      {imagePreview ? "Change Photo" : "Add Photo"}
                    </span>
                  </BtnSecondary>
                  {imagePreview && (
                    <div className="relative">
                      <img src={imagePreview} alt="Preview" className="w-16 h-16 object-cover rounded-lg border border-gray-300 dark:border-gray-600" />
                      <button
                        onClick={() => { setImageFile(null); setImagePreview(null); if (fileInputRef.current) fileInputRef.current.value = ""; }}
                        className="absolute -top-2 -right-2 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center"
                      >✕</button>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex items-center gap-3">
                <BtnPrimary onClick={() => setDraft({ itemName: textInput.trim() || "", category: "Other", location: "", notes: "", confidence: 0 })}>
                  Next
                </BtnPrimary>
                <button
                  onClick={handleAiStructure}
                  disabled={aiLoading || !textInput.trim()}
                  title="Auto-fill with AI"
                  className="p-2 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
                >
                  {aiLoading
                    ? <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/></svg>
                    : <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                  }
                </button>
                <span className="text-xs text-gray-400">AI</span>
              </div>
            </div>
          ) : (
            <div className="space-y-3">
              {imagePreview && <img src={imagePreview} alt="Preview" className="w-full h-40 object-cover rounded-lg" />}
              <div>
                <Label>Item Name</Label>
                <Input value={draft.itemName} onChange={e => setDraft({...draft, itemName: e.target.value})} />
              </div>
              <div>
                <Label>Category</Label>
                <Select value={draft.category} onChange={e => setDraft({...draft, category: e.target.value})}>
                  {ITEM_CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                </Select>
              </div>
              <div>
                <Label>Location</Label>
                {locationNames.length > 0 ? (
                  <LocationSelect value={draft.location} onChange={e => setDraft({...draft, location: e.target.value})} />
                ) : (
                  <>
                    <Input value={draft.location} onChange={e => setDraft({...draft, location: e.target.value})} placeholder="Where is this item?" />
                    <p className="text-xs text-gray-400 mt-1">
                      Tip: set up named locations in the <button className="underline" onClick={() => { resetModal(); setTab("locations"); }}>Locations tab</button> to use a dropdown here.
                    </p>
                  </>
                )}
              </div>
              <div>
                <Label>Notes</Label>
                <Textarea rows={2} value={draft.notes} onChange={e => setDraft({...draft, notes: e.target.value})} />
              </div>
              <p className="text-xs text-gray-500">AI Confidence: {Math.round(draft.confidence * 100)}%</p>
              <div className="flex gap-3">
                <BtnPrimary onClick={saveDraft} disabled={uploading}>
                  {uploading ? "Saving..." : "Save Item"}
                </BtnPrimary>
                <BtnSecondary onClick={() => setDraft(null)}>Back</BtnSecondary>
              </div>
            </div>
          )}
        </Modal>
      )}
    </section>
  );
};

window.ItemsScreen = ItemsScreen;
