import type XLSX from "xlsx"
import { useCallback, useState, useContext } from "react"
import { useRsi } from "../../hooks/useRsi"
import { DropZone } from "./components/DropZone"
import { StepType } from "../UploadFlow"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import { AuthContext } from "@/contexts/AuthContext"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Bug } from "lucide-react"
import { v4 as uuidv4 } from "uuid"
import { SavedSessionsList } from "../../components/SavedSessionsList"
import type { ImportSession } from "@/types/importSession"

type UploadProps = {
  onContinue: (data: XLSX.WorkBook, file: File) => Promise<void>
  setInitialState?: (state: { type: StepType; data: any[]; isFromScratch?: boolean }) => void
  onRestoreSession?: (session: ImportSession) => void
}

const OrSeparator = () => (
  <div className="flex items-center justify-center">
    <Separator className="w-24" />
    <span className="px-3 text-muted-foreground text-sm font-medium">OR</span>
    <Separator className="w-24" />
  </div>
)

export const UploadStep = ({ onContinue, setInitialState, onRestoreSession }: UploadProps) => {
  const [isLoading, setIsLoading] = useState(false)
  const { translations } = useRsi()
  const { user } = useContext(AuthContext)
  const hasDebugPermission = Boolean(user?.is_admin || user?.permissions?.includes("admin:debug"))

  const [jsonInput, setJsonInput] = useState("")
  const [jsonError, setJsonError] = useState<string | null>(null)

  const handleOnContinue = useCallback(
    async (data: XLSX.WorkBook, file: File) => {
      setIsLoading(true)
      await onContinue(data, file)
      setIsLoading(false)
    },
    [onContinue],
  )

  const handleStartFromScratch = useCallback(() => {
    if (setInitialState) {
      setInitialState({ type: StepType.validateData, data: [{}], isFromScratch: true })
    }
  }, [setInitialState])

  const handleJsonImport = useCallback(() => {
    setJsonError(null)
    try {
      const parsed = JSON.parse(jsonInput)

      // Handle both array and object with products property
      const products: any[] = Array.isArray(parsed) ? parsed : parsed.products

      if (!Array.isArray(products) || products.length === 0) {
        setJsonError("JSON must be an array of products or an object with a 'products' array")
        return
      }

      // Add __index to each row if not present (required for validation step)
      const dataWithIndex = products.map((row: any) => ({
        ...row,
        __index: row.__index || uuidv4()
      }))

      if (setInitialState) {
        setInitialState({
          type: StepType.validateData,
          data: dataWithIndex,
          isFromScratch: true
        })
      }
    } catch (e) {
      setJsonError(`Invalid JSON: ${e instanceof Error ? e.message : "Parse error"}`)
    }
  }, [jsonInput, setInitialState])

  return (
    <div className="p-8">
      <h2 className="text-3xl font-semibold mb-8 text-left">{translations.uploadStep.title}</h2>
      <div className="max-w-xl mx-auto w-full space-y-8">
        {hasDebugPermission && (
          <>
            <div className="rounded-lg border border-amber-600/40 p-6 space-y-3">
              <Label htmlFor="import-json" className="flex items-center gap-2 text-amber-600 font-semibold">
                <Bug className="h-4 w-4" />
                Import JSON
              </Label>
              <p className="text-sm text-muted-foreground">
                Paste product data in the same JSON format as the API submission. The data will be loaded into the validation step.
              </p>
              <Textarea
                id="import-json"
                placeholder='[{"supplier": "...", "company": "...", "name": "...", "product_images": "url1,url2", ...}]'
                value={jsonInput}
                onChange={(e) => {
                  setJsonInput(e.target.value)
                  setJsonError(null)
                }}
                className="min-h-[160px] font-mono text-sm"
              />
              {jsonError && (
                <p className="text-sm text-destructive">{jsonError}</p>
              )}
              <div className="flex justify-end">
                <Button
                  onClick={handleJsonImport}
                  disabled={!setInitialState || !jsonInput.trim()}
                  className="bg-amber-600 hover:bg-amber-700"
                >
                  Import & Go to Validation
                </Button>
              </div>
            </div>

            <OrSeparator />
          </>
        )}

        <div className="rounded-lg p-6 flex flex-col items-center">
          <DropZone onContinue={handleOnContinue} isLoading={isLoading} />
        </div>

        <OrSeparator />

        <div className="flex justify-center pb-8">
          <Button
            onClick={handleStartFromScratch}
            variant="outline"
            className="min-w-[200px]"
            disabled={!setInitialState}
          >
            Start from scratch
          </Button>
        </div>

        {/* Saved sessions list */}
        {onRestoreSession && (
          <SavedSessionsList onRestore={onRestoreSession} />
        )}
      </div>
    </div>
  )
}
