import { RefreshCw } from "lucide-react";
import { useInventoryViewModel } from "./hooks/useInventoryViewModel";
import type { InventoryViewProps } from "./types";

export function InventoryView({ snapshot }: InventoryViewProps) {
  const {
    rows,
    selectedRow,
    selectedPreview,
    previewStatus,
    filter,
    sort,
    loading,
    statusText,
    promotionStatus,
    promotionPending,
    promotionConfirming,
    reviewEditing,
    reviewPending,
    reviewStatus,
    reviewDraft,
    totalRows,
    nativeCount,
    storedCount,
    reviewCount,
    catalogSummary,
    promotionSummary,
    pipelineSummary,
    filterOptions,
    sortOptions,
    setFilter,
    setSort,
    setSelectedId,
    refresh,
    requestSelectedPromotion,
    cancelSelectedPromotion,
    confirmSelectedPromotion,
    startSelectedReview,
    cancelSelectedReview,
    setReviewDraft,
    submitSelectedReview,
  } = useInventoryViewModel({ snapshot });

  return (
    <section className="inventory-view">
      <div className="inventory-toolbar">
        <div>
          <p className="eyebrow">Native Artifact Inventory</p>
          <h2>Artifact Scan-Ergebnisse</h2>
        </div>
        <div className="inventory-toolbar-actions">
          <div className="inventory-stats">
            <span>{totalRows} gesamt</span>
            <span>{nativeCount} native</span>
            <span>{storedCount} store</span>
            <span>{reviewCount} review</span>
          </div>
          <button className="ghost-button icon-button" onClick={() => void refresh()} disabled={loading} title="Inventory aktualisieren">
            <RefreshCw size={16} />
          </button>
        </div>
      </div>

      <div className={`inventory-catalog-strip ${catalogSummary.className}`}>
        <div>
          <span>{catalogSummary.ok ? "Artifact IK bereit" : "IK Listen pruefen"}</span>
          <strong>{catalogSummary.title}</strong>
          <small>{catalogSummary.detail}</small>
        </div>
        {catalogSummary.counts.length > 0 && (
          <div className="inventory-catalog-counts">
            {catalogSummary.counts.map((entry) => (
              <span key={entry.label}>
                <strong>{entry.value}</strong>
                <small>{entry.label}</small>
                {entry.sample && <em>{entry.sample}</em>}
              </span>
            ))}
          </div>
        )}
      </div>

      <div className="inventory-pipeline-strip" aria-label="Native artifact pipeline status">
        {pipelineSummary.cards.map((card) => (
          <span key={card.id} className={card.className} title={card.detail}>
            <strong>{card.title}</strong>
            <small>{card.value}</small>
            <em>{card.detail}</em>
          </span>
        ))}
      </div>
      <p className="inventory-pipeline-caption">{pipelineSummary.caption}</p>

      <div className={`inventory-promotion-strip ${promotionSummary.className}`}>
        <div>
          <span>{promotionSummary.title}</span>
          <strong>{promotionSummary.detail}</strong>
          <small>Analyse aus scan-results.json und lokalem Artifact-Store. Store-Schreibzugriff bleibt ein expliziter naechster Schritt.</small>
        </div>
        <div className="inventory-promotion-counts">
          <span><strong>{promotionSummary.ready}</strong><small>Speicherbar</small></span>
          <span><strong>{promotionSummary.alreadyStored + promotionSummary.persisted}</strong><small>Im Store</small></span>
          <span><strong>{promotionSummary.review}</strong><small>Review</small></span>
          <span><strong>{promotionSummary.blocked}</strong><small>Blockiert</small></span>
        </div>
      </div>

      <div className="inventory-controls">
        <div className="segmented-control">
          {filterOptions.map((option) => (
            <button
              key={option.id}
              className={filter === option.id ? "active" : ""}
              onClick={() => setFilter(option.id)}
            >
              {option.label} <span>{option.count}</span>
            </button>
          ))}
        </div>
        <label className="inventory-sort">
          <span>Sort</span>
          <select value={sort} onChange={(event) => setSort(event.target.value as typeof sort)}>
            {sortOptions.map((option) => (
              <option key={option.id} value={option.id}>{option.label}</option>
            ))}
          </select>
        </label>
      </div>

      <div className="inventory-browser">
        <div className="inventory-list" aria-label="Artifact inventory results">
          {rows.length > 0 ? rows.map((row) => (
            <button
              key={row.id}
              className={`inventory-row ${selectedRow?.id === row.id ? "active" : ""}`}
              onClick={() => setSelectedId(row.id)}
            >
              <span className="inventory-row-sequence">{row.sequenceLabel}</span>
              <span className="inventory-row-main">
                <strong>{row.title}</strong>
                <span>{row.slot} - {row.mainStat} {row.mainValue} - {row.levelLabel}</span>
              </span>
              <span className="inventory-row-source">{row.sourceLabel}</span>
              <span className={`result-rail-status ${row.statusClassName}`}>{row.statusLabel}</span>
            </button>
          )) : (
            <p className="inventory-empty">Keine Scan-Ergebnisse geladen.</p>
          )}
        </div>

        <aside className="inventory-detail">
          {selectedRow ? (
            <>
              <div className="inventory-detail-heading">
                <p className="eyebrow">{selectedRow.sourceLabel} {selectedRow.sequenceLabel}</p>
                <h3>{selectedRow.title}</h3>
                <span className={`result-rail-status ${selectedRow.statusClassName}`}>{selectedRow.statusLabel}</span>
              </div>
              <div className={`inventory-action-card ${selectedRow.nextActionClassName}`}>
                <span>Naechster Schritt</span>
                <strong>{selectedRow.nextActionLabel}</strong>
                <small>{selectedRow.nextActionDetail}</small>
                {selectedRow.canPromote && !promotionConfirming && (
                  <button className="primary-button inventory-promote-button" onClick={requestSelectedPromotion} disabled={promotionPending}>
                    Ausgewaehltes Ergebnis promoten
                  </button>
                )}
                {selectedRow.canPromote && promotionConfirming && (
                  <div className="inventory-promotion-confirm">
                    <strong>Dieses gepruefte Ergebnis jetzt in den lokalen Store schreiben?</strong>
                    <div>
                      <button className="primary-button" onClick={() => void confirmSelectedPromotion()} disabled={promotionPending}>Bestaetigen</button>
                      <button className="ghost-button" onClick={cancelSelectedPromotion} disabled={promotionPending}>Abbrechen</button>
                    </div>
                  </div>
                )}
                {selectedRow.source === "native" && selectedRow.needsReview && !reviewEditing && (
                  <button className="primary-button inventory-promote-button" onClick={startSelectedReview} disabled={reviewPending}>
                    Review bearbeiten
                  </button>
                )}
              </div>
              {reviewEditing && reviewDraft && (
                <div className="inventory-review-editor">
                  <div className="inventory-review-heading">
                    <div>
                      <span>Manuelle Korrektur</span>
                      <strong>Crop pruefen, Felder korrigieren, dann freigeben oder ablehnen.</strong>
                    </div>
                    <button className="ghost-button" onClick={cancelSelectedReview} disabled={reviewPending}>Schliessen</button>
                  </div>
                  <div className="inventory-review-grid">
                    <label><span>Name</span><input value={reviewDraft.name} onChange={(event) => setReviewDraft({ ...reviewDraft, name: event.target.value })} /></label>
                    <label><span>Set</span><input value={reviewDraft.setName} onChange={(event) => setReviewDraft({ ...reviewDraft, setName: event.target.value })} /></label>
                    <label><span>Slot</span><select value={reviewDraft.slot} onChange={(event) => setReviewDraft({ ...reviewDraft, slot: event.target.value })}>
                      {["Flower of Life", "Plume of Death", "Sands of Eon", "Goblet of Eonothem", "Circlet of Logos"].map((slot) => <option key={slot}>{slot}</option>)}
                    </select></label>
                    <label><span>Level</span><input type="number" min="0" max="20" value={reviewDraft.level} onChange={(event) => setReviewDraft({ ...reviewDraft, level: event.target.value })} /></label>
                    <label><span>Main Stat</span><input value={reviewDraft.mainStat} onChange={(event) => setReviewDraft({ ...reviewDraft, mainStat: event.target.value })} /></label>
                    <label><span>Main Value</span><input value={reviewDraft.mainValue} onChange={(event) => setReviewDraft({ ...reviewDraft, mainValue: event.target.value })} /></label>
                    <label><span>Equipped</span><input value={reviewDraft.equipped} onChange={(event) => setReviewDraft({ ...reviewDraft, equipped: event.target.value })} /></label>
                    <label className="inventory-review-lock"><input type="checkbox" checked={reviewDraft.locked} onChange={(event) => setReviewDraft({ ...reviewDraft, locked: event.target.checked })} /><span>Locked</span></label>
                    <label className="inventory-review-wide"><span>Substats, eine Zeile pro Wert</span><textarea rows={4} value={reviewDraft.substats} onChange={(event) => setReviewDraft({ ...reviewDraft, substats: event.target.value })} /></label>
                    <label className="inventory-review-wide"><span>Review-Notiz</span><input value={reviewDraft.note} onChange={(event) => setReviewDraft({ ...reviewDraft, note: event.target.value })} /></label>
                  </div>
                  <div className="inventory-review-actions">
                    <button className="primary-button" onClick={() => void submitSelectedReview("approve")} disabled={reviewPending}>Korrektur freigeben</button>
                    <button className="ghost-button danger" onClick={() => void submitSelectedReview("reject")} disabled={reviewPending}>Ergebnis ablehnen</button>
                  </div>
                </div>
              )}
              <div className={`inventory-preview ${selectedPreview ? "has-preview" : "is-empty"}`}>
                {selectedPreview ? (
                  <img src={selectedPreview.dataUrl} alt={`Preview ${selectedRow.title}`} />
                ) : (
                  <span>{previewStatus || "Kein Crop-Preview geladen"}</span>
                )}
              </div>
              {previewStatus && selectedPreview && <p className="inventory-preview-status">{previewStatus}</p>}
              <div className="inventory-detail-grid">
                <span>Set</span><strong>{selectedRow.setName}</strong>
                <span>Slot</span><strong>{selectedRow.slot}</strong>
                <span>Main</span><strong>{selectedRow.mainStat} {selectedRow.mainValue}</strong>
                <span>Level</span><strong>{selectedRow.levelLabel}</strong>
                <span>Value</span><strong>{selectedRow.valueLabel}</strong>
                <span>IK</span><strong>{selectedRow.ikLabel}</strong>
                <span>GOOD</span><strong>{selectedRow.ikGoodLabel}</strong>
                <span>Promotion</span><strong>{selectedRow.promotionLabel}</strong>
                <span>Confidence</span><strong>{selectedRow.confidence}%</strong>
                <span>Equipped</span><strong>{selectedRow.equipped}</strong>
              </div>
              <div className="inventory-substats">
                {selectedRow.substats.length > 0 ? selectedRow.substats.map((substat) => (
                  <span key={`${selectedRow.id}-${substat}`}>{substat}</span>
                )) : <span>Keine Substats gelesen</span>}
              </div>
              {selectedRow.fieldConfidences.length > 0 && (
                <div className="inventory-field-confidence">
                  {selectedRow.fieldConfidences.map((field) => (
                    <span key={`${selectedRow.id}-${field.key}`} className={field.confidence < 70 ? "low" : field.confidence < 86 ? "medium" : "high"}>
                      <strong>{field.confidence}%</strong>
                      <small>{field.label} · {field.source}</small>
                    </span>
                  ))}
                </div>
              )}
              {(selectedRow.notes.length > 0 || selectedRow.promotionReasons.length > 0 || selectedRow.error || selectedRow.imagePath || selectedRow.promotionRecordId) && (
                <div className="inventory-notes">
                  {selectedRow.imagePath && <span>{selectedRow.imagePath}</span>}
                  {selectedRow.promotionRecordId && <span>{selectedRow.promotionRecordId}</span>}
                  {selectedRow.error && <strong>{selectedRow.error}</strong>}
                  {selectedRow.promotionReasons.map((reason) => <span key={`${selectedRow.id}-promotion-${reason}`}>{reason}</span>)}
                  {selectedRow.notes.map((note) => <span key={`${selectedRow.id}-${note}`}>{note}</span>)}
                </div>
              )}
            </>
          ) : (
            <p className="inventory-empty">Waehle ein Ergebnis aus.</p>
          )}
        </aside>
      </div>
      <p className="inventory-status">{statusText}</p>
      {promotionStatus && <p className="inventory-status">{promotionStatus}</p>}
      {reviewStatus && <p className="inventory-status">{reviewStatus}</p>}
    </section>
  );
}
