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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
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
}

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"))

  // Debug import state
  const [debugDialogOpen, setDebugDialogOpen] = useState(false)
  const [debugJsonInput, setDebugJsonInput] = useState("")
  const [debugError, setDebugError] = 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 handleDebugImport = useCallback(() => {
    setDebugError(null)
    try {
      const parsed = JSON.parse(debugJsonInput)

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

      if (!Array.isArray(products) || products.length === 0) {
        setDebugError("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
        })
      }

      setDebugDialogOpen(false)
      setDebugJsonInput("")
    } catch (e) {
      setDebugError(`Invalid JSON: ${e instanceof Error ? e.message : "Parse error"}`)
    }
  }, [debugJsonInput, setInitialState])
  
  return (
    <div className="p-8">
      <div className="flex items-baseline justify-between">
      <h2 className="text-3xl font-semibold mb-8 text-left">{translations.uploadStep.title}</h2>
              {hasDebugPermission && (
          <>
            

            <div className="flex justify-center">
              <Button
                onClick={() => setDebugDialogOpen(true)}
                variant="outline"
                className="min-w-[200px] text-amber-600 border-amber-600 hover:bg-amber-50"
                disabled={!setInitialState}
              >
                <Bug className="mr-2 h-4 w-4" />
                Import JSON
              </Button>
            </div>
          </>
        )}
        </div>
      <div className="max-w-xl mx-auto w-full space-y-8">
        <div className="rounded-lg p-6 flex flex-col items-center">
          <DropZone onContinue={handleOnContinue} isLoading={isLoading} />
        </div>
        
        <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>
        
        <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>

      <Dialog open={debugDialogOpen} onOpenChange={setDebugDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[80vh]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-amber-600">
              <Bug className="h-5 w-5" />
              Debug: Import JSON Data
            </DialogTitle>
            <DialogDescription>
              Paste product data in the same JSON format as the API submission. The data will be loaded into the validation step.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="debug-json">Product JSON</Label>
              <Textarea
                id="debug-json"
                placeholder='[{"supplier": "...", "company": "...", "name": "...", "product_images": "url1,url2", ...}]'
                value={debugJsonInput}
                onChange={(e) => {
                  setDebugJsonInput(e.target.value)
                  setDebugError(null)
                }}
                className="min-h-[300px] font-mono text-sm"
              />
              {debugError && (
                <p className="text-sm text-destructive">{debugError}</p>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDebugDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleDebugImport}
              disabled={!debugJsonInput.trim()}
              className="bg-amber-600 hover:bg-amber-700"
            >
              Import & Go to Validation
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
