import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
  Loader2,
  Check,
  X,
  ExternalLink,
  Sparkles,
  AlertCircle,
  Save,
  CheckCircle,
  AlertTriangle,
} from "lucide-react";
import { cn } from "@/lib/utils";
import type { SearchProduct, FieldOption } from "@/components/product-editor/types";

const PROD_IMG_HOST = "https://sbing.com";
const BACKEND_URL = "https://backend.acherryontop.com/product";

export type BulkEditFieldChoice =
  | "name"
  | "description"
  | "categories"
  | "themes"
  | "colors"
  | "tax_cat"
  | "size_cat"
  | "ship_restrictions"
  | "hts_code"
  | "weight"
  | "msrp"
  | "cost_each";

export interface AiResult {
  isValid: boolean;
  suggestion?: string | null;
  issues: string[];
}

export interface RowAiState {
  status: "idle" | "validating" | "done";
  result: AiResult | null;
  editedSuggestion: string | null;
  decision: "accepted" | "dismissed" | null;
  saveStatus: "idle" | "saving" | "saved" | "error";
  saveError: string | null;
  /** Track manual edits to the main field value */
  manualEdit: string | null;
}

export const INITIAL_ROW_STATE: RowAiState = {
  status: "idle",
  result: null,
  editedSuggestion: null,
  decision: null,
  saveStatus: "idle",
  saveError: null,
  manualEdit: null,
};

/** Fields that support AI validation */
export const AI_FIELDS: BulkEditFieldChoice[] = ["name", "description"];

/** Field display config */
export const FIELD_OPTIONS: { value: BulkEditFieldChoice; label: string; ai?: boolean }[] = [
  { value: "description", label: "Description", ai: true },
  { value: "name", label: "Name", ai: true },
  { value: "hts_code", label: "HTS Code" },
  { value: "weight", label: "Weight" },
  { value: "msrp", label: "MSRP" },
  { value: "cost_each", label: "Cost Each" },
  { value: "tax_cat", label: "Tax Category" },
  { value: "size_cat", label: "Size Category" },
  { value: "ship_restrictions", label: "Shipping Restrictions" },
];

/** Get the current raw value for a field from SearchProduct */
export function getFieldValue(product: SearchProduct, field: BulkEditFieldChoice): string {
  switch (field) {
    case "name": return product.title ?? "";
    case "description": return product.description ?? "";
    case "hts_code": return product.harmonized_tariff_code ?? "";
    case "weight": return product.weight != null ? String(product.weight) : "";
    case "msrp": return product.regular_price != null ? String(product.regular_price) : "";
    case "cost_each": return product.cost_price != null ? String(product.cost_price) : "";
    case "tax_cat": return product.tax_code ?? "";
    case "size_cat": return product.size_cat ?? "";
    case "ship_restrictions": return product.shipping_restrictions ?? "";
    default: return "";
  }
}

/** Get the product editor API field key for submission */
export function getSubmitFieldKey(field: BulkEditFieldChoice): string {
  return field;
}

interface BulkEditRowProps {
  product: SearchProduct;
  field: BulkEditFieldChoice;
  state: RowAiState;
  imageUrl: string | null;
  selectOptions?: FieldOption[];
  onAccept: (pid: number, value: string) => void;
  onDismiss: (pid: number) => void;
  onManualEdit: (pid: number, value: string) => void;
  onEditSuggestion: (pid: number, value: string) => void;
}

export function BulkEditRow({
  product,
  field,
  state,
  imageUrl,
  selectOptions,
  onAccept,
  onDismiss,
  onManualEdit,
  onEditSuggestion,
}: BulkEditRowProps) {
  const currentValue = state.manualEdit ?? getFieldValue(product, field);
  const hasAiSuggestion =
    state.status === "done" && state.result && !state.result.isValid && state.result.suggestion;
  const isValid = state.status === "done" && state.result?.isValid;
  const isAccepted = state.decision === "accepted";
  const isDismissed = state.decision === "dismissed";
  const isValidating = state.status === "validating";
  const showSuggestion = hasAiSuggestion && !isDismissed && !isAccepted;
  const backendUrl = `${BACKEND_URL}/${product.pid}`;

  // Determine border color based on state
  const borderClass = isAccepted
    ? "border-l-4 border-l-green-500"
    : state.saveStatus === "saved"
      ? "border-l-4 border-l-green-300"
      : state.saveStatus === "error"
        ? "border-l-4 border-l-destructive"
        : "";

  const renderFieldEditor = () => {
    // If this is a select field, render a select
    if (selectOptions) {
      return (
        <Select
          value={currentValue}
          onValueChange={(v) => onManualEdit(product.pid, v)}
        >
          <SelectTrigger className="w-full h-8 text-sm">
            <SelectValue placeholder="Select..." />
          </SelectTrigger>
          <SelectContent>
            {selectOptions.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                {opt.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      );
    }

    // Description gets a textarea with inline spinner
    if (field === "description") {
      return (
        <div className="relative">
          <Textarea
            value={currentValue}
            onChange={(e) => onManualEdit(product.pid, e.target.value)}
            className={cn(
              "text-sm min-h-[60px] max-h-[120px] resize-y",
              isValidating && "pr-8"
            )}
            rows={2}
          />
          {isValidating && (
            <Loader2 className="absolute top-2 right-2 h-4 w-4 animate-spin text-purple-500" />
          )}
        </div>
      );
    }

    // Name/text fields with inline spinner
    return (
      <div className="relative">
        <Input
          value={currentValue}
          onChange={(e) => onManualEdit(product.pid, e.target.value)}
          className={cn("h-8 text-sm", isValidating && "pr-8")}
        />
        {isValidating && (
          <Loader2 className="absolute top-2 right-2 h-3.5 w-3.5 animate-spin text-purple-500" />
        )}
      </div>
    );
  };

  // Inline AI suggestion panel for name / short text fields
  const renderNameSuggestion = () => {
    if (!showSuggestion) return null;

    return (
      <div className="flex flex-col gap-1.5 min-w-0 flex-1">
        {/* Issues */}
        {state.result!.issues.length > 0 && (
          <div className="flex flex-col gap-0.5">
            {state.result!.issues.map((issue, i) => (
              <div
                key={i}
                className="flex items-start gap-1 text-[11px] text-purple-600 dark:text-purple-400"
              >
                <AlertCircle className="h-3 w-3 mt-0.5 flex-shrink-0 text-purple-400" />
                <span>{issue}</span>
              </div>
            ))}
          </div>
        )}
        {/* Editable suggestion + actions */}
        <div className="flex items-center gap-1.5">
          <Sparkles className="h-3.5 w-3.5 text-purple-500 shrink-0" />
          <Input
            value={state.editedSuggestion ?? state.result!.suggestion!}
            onChange={(e) => onEditSuggestion(product.pid, e.target.value)}
            className="h-7 text-sm flex-1 border-purple-200 dark:border-purple-700 focus-visible:ring-purple-400 bg-purple-50/50 dark:bg-purple-950/20"
          />
          <Button
            size="sm"
            variant="outline"
            className="h-7 px-2 text-xs shrink-0 bg-white border-green-300 text-green-700 hover:bg-green-50 hover:border-green-400 dark:bg-green-950/30 dark:border-green-700 dark:text-green-400"
            onClick={() =>
              onAccept(product.pid, state.editedSuggestion ?? state.result!.suggestion!)
            }
          >
            <Check className="h-3 w-3 mr-1" />
            Accept
          </Button>
          <Button
            size="sm"
            variant="ghost"
            className="h-7 px-1.5 text-xs text-gray-500 hover:text-gray-700 shrink-0"
            onClick={() => onDismiss(product.pid)}
          >
            <X className="h-3 w-3" />
          </Button>
        </div>
      </div>
    );
  };

  // Inline AI suggestion panel for description (larger, stacked)
  const renderDescriptionSuggestion = () => {
    if (!showSuggestion) return null;

    return (
      <div className="flex flex-col gap-1.5 min-w-0 flex-1 bg-purple-50/60 dark:bg-purple-950/20 rounded-md p-2">
        {/* Header */}
        <div className="flex items-center gap-1.5">
          <Sparkles className="h-3.5 w-3.5 text-purple-500" />
          <span className="text-xs font-medium text-purple-600 dark:text-purple-400">
            AI Suggestion
          </span>
          {state.result!.issues.length > 0 && (
            <span className="text-[11px] text-purple-500">
              ({state.result!.issues.length} {state.result!.issues.length === 1 ? "issue" : "issues"})
            </span>
          )}
        </div>

        {/* Issues */}
        {state.result!.issues.length > 0 && (
          <div className="flex flex-col gap-0.5">
            {state.result!.issues.map((issue, i) => (
              <div
                key={i}
                className="flex items-start gap-1 text-[11px] text-purple-600 dark:text-purple-400"
              >
                <AlertCircle className="h-3 w-3 mt-0.5 flex-shrink-0 text-purple-400" />
                <span>{issue}</span>
              </div>
            ))}
          </div>
        )}

        {/* Editable suggestion */}
        <Textarea
          value={state.editedSuggestion ?? state.result!.suggestion!}
          onChange={(e) => onEditSuggestion(product.pid, e.target.value)}
          className="text-sm min-h-[60px] max-h-[120px] resize-y border-purple-200 dark:border-purple-700 focus-visible:ring-purple-400 bg-white dark:bg-black/20"
          rows={2}
        />

        {/* Actions */}
        <div className="flex items-center gap-1.5">
          <Button
            size="sm"
            variant="outline"
            className="h-7 px-2 text-xs bg-white border-green-300 text-green-700 hover:bg-green-50 hover:border-green-400 dark:bg-green-950/30 dark:border-green-700 dark:text-green-400"
            onClick={() =>
              onAccept(product.pid, state.editedSuggestion ?? state.result!.suggestion!)
            }
          >
            <Check className="h-3 w-3 mr-1" />
            Accept
          </Button>
          <Button
            size="sm"
            variant="ghost"
            className="h-7 px-2 text-xs text-gray-500 hover:text-gray-700"
            onClick={() => onDismiss(product.pid)}
          >
            Dismiss
          </Button>
        </div>
      </div>
    );
  };

  // Status icon (right edge)
  const renderStatus = () => {
    // Don't show spinner here anymore — it's in the field editor
    if (isValid && !isAccepted) {
      return (
        <Tooltip>
          <TooltipTrigger asChild>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </TooltipTrigger>
          <TooltipContent>No changes needed</TooltipContent>
        </Tooltip>
      );
    }
    if (isAccepted) {
      return (
        <Tooltip>
          <TooltipTrigger asChild>
            <Check className="h-4 w-4 text-green-600" />
          </TooltipTrigger>
          <TooltipContent>Change accepted</TooltipContent>
        </Tooltip>
      );
    }
    if (state.saveStatus === "saving") {
      return <Loader2 className="h-4 w-4 animate-spin text-primary" />;
    }
    if (state.saveStatus === "saved") {
      return (
        <Tooltip>
          <TooltipTrigger asChild>
            <Save className="h-4 w-4 text-green-500" />
          </TooltipTrigger>
          <TooltipContent>Saved</TooltipContent>
        </Tooltip>
      );
    }
    if (state.saveStatus === "error") {
      return (
        <Tooltip>
          <TooltipTrigger asChild>
            <AlertTriangle className="h-4 w-4 text-destructive" />
          </TooltipTrigger>
          <TooltipContent>{state.saveError || "Save failed"}</TooltipContent>
        </Tooltip>
      );
    }
    return null;
  };

  return (
    <div className={cn("rounded-lg border bg-card transition-colors", borderClass)}>
      <div className="flex items-start gap-3 p-3">
        {/* Thumbnail */}
        <a
          href={backendUrl}
          target="_blank"
          rel="noreferrer"
          className="block h-12 w-12 shrink-0 overflow-hidden rounded-md border bg-muted"
        >
          {imageUrl ? (
            <img
              src={imageUrl.startsWith("/") ? PROD_IMG_HOST + imageUrl : imageUrl}
              alt={product.title}
              className="h-full w-full object-cover"
              loading="lazy"
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center text-[10px] text-muted-foreground">
              No img
            </div>
          )}
        </a>

        {/* Identity */}
        <div className="flex flex-col gap-0.5 min-w-0 w-44 shrink-0">
          <a
            href={backendUrl}
            target="_blank"
            rel="noreferrer"
            className="text-sm font-medium text-primary hover:underline flex items-center gap-1 truncate"
          >
            <span className="truncate">{product.title}</span>
            <ExternalLink className="h-3 w-3 shrink-0" />
          </a>
          <span className="text-xs text-muted-foreground truncate">
            UPC: {product.barcode || "—"}
          </span>
          <span className="text-xs text-muted-foreground truncate">
            SKU: {product.sku || "—"}
          </span>
        </div>

        {/* Field editor */}
        <div className="min-w-0 flex-1">
          {renderFieldEditor()}
        </div>

        {/* AI suggestion inline (same row) */}
        {field === "description"
          ? renderDescriptionSuggestion()
          : renderNameSuggestion()
        }

        {/* Status icon */}
        <div className="flex items-center shrink-0 w-6 justify-center pt-1">
          {renderStatus()}
        </div>
      </div>
    </div>
  );
}
