import { useState, useEffect, useMemo } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Folder, AlertCircle } from 'lucide-react'
import {
  heaps as heapsApi,
  type Heap,
  type FolderTreeNode,
} from '../../services/api'
import { HEAPS_QUERY_KEY } from '../../hooks/useHeapsQuery'
import { useFolderTreeQuery } from '../../hooks/useFolderTreeQuery'
import { toast } from '../ToastContainer'
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Checkbox } from '@/components/ui/checkbox'
import { Alert, AlertDescription } from '@/components/ui/alert'

interface FlatFolder {
  id: string
  name: string
  path: string
  depth: number
}

/** Walk the folder tree depth-first into a flat list with depth info so
 *  the picker can render every node — including nested subfolders — as
 *  one indented option. */
function flattenTree(nodes: FolderTreeNode[], depth = 0): FlatFolder[] {
  const out: FlatFolder[] = []
  for (const n of nodes) {
    out.push({ id: n.id, name: n.name, path: n.path, depth })
    if (n.children.length > 0) {
      out.push(...flattenTree(n.children, depth + 1))
    }
  }
  return out
}

interface HeapConvertDialogProps {
  heap: Heap | null
  onClose: () => void
}

export function HeapConvertDialog({ heap, onClose }: HeapConvertDialogProps) {
  const queryClient = useQueryClient()
  const [targetId, setTargetId] = useState('')
  const [mode, setMode] = useState<'move' | 'copy'>('move')
  const [deleteHeap, setDeleteHeap] = useState(false)
  const [subfolderName, setSubfolderName] = useState('')

  const { data: tree = [] } = useFolderTreeQuery()
  const folders = useMemo<FlatFolder[]>(() => flattenTree(tree), [tree])

  useEffect(() => {
    if (!targetId && folders.length > 0) {
      setTargetId(folders[0].id)
    }
  }, [folders, targetId])

  useEffect(() => {
    if (heap) {
      setSubfolderName(heap.name)
    } else {
      setTargetId('')
      setMode('move')
      setDeleteHeap(false)
      setSubfolderName('')
    }
  }, [heap])

  const convertMutation = useMutation({
    mutationFn: () =>
      heapsApi.convert(heap!.id, {
        target_id: targetId,
        mode,
        delete_heap: deleteHeap,
        subfolder_name: subfolderName.trim() || null,
      }),
    onSuccess: (data) => {
      const total = (data.moved ?? 0) + (data.copied ?? 0)
      const verb = data.mode === 'move' ? 'Moved' : 'Copied'
      toast.success(
        `${verb} ${total} photo${total === 1 ? '' : 's'}`,
        data.heap_deleted ? `Heap "${heap?.name}" deleted` : undefined
      )
      queryClient.invalidateQueries({ queryKey: HEAPS_QUERY_KEY })
      queryClient.invalidateQueries({ queryKey: ['photos'] })
      queryClient.invalidateQueries({ queryKey: ['folders'] })
      onClose()
    },
    onError: (e: any) =>
      toast.error('Convert failed', e?.response?.data?.detail || e.message),
  })

  const targetFolder = folders.find((f) => f.id === targetId)

  return (
    <Dialog open={!!heap} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Convert "{heap?.name}" to folder</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Target picker */}
          <div className="space-y-1.5">
            <Label>Target folder</Label>
            {folders.length === 0 ? (
              <div className="rounded border border-border bg-bg px-3 py-2 text-xs text-text-muted">
                No folders available
              </div>
            ) : (
              <Select value={targetId} onValueChange={setTargetId}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {folders.map((f) => (
                    <SelectItem key={f.id} value={f.id}>
                      {'\u00A0\u00A0'.repeat(f.depth) + f.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
            {targetFolder && (
              <p className="flex items-center gap-1 text-xs text-text-faint">
                <Folder className="h-3 w-3" />
                {targetFolder.path}
              </p>
            )}
          </div>

          {/* Subfolder name */}
          <div className="space-y-1.5">
            <Label htmlFor="heap-convert-subfolder">Subfolder name</Label>
            <Input
              id="heap-convert-subfolder"
              type="text"
              value={subfolderName}
              onChange={(e) => setSubfolderName(e.target.value)}
              placeholder="(none — use parent directly)"
            />
            <p className="text-xs text-text-faint">
              {subfolderName.trim() && targetFolder
                ? `Will create ${targetFolder.path}/${subfolderName.trim()} if missing.`
                : 'Photos go directly into the parent folder.'}
            </p>
          </div>

          {/* Mode */}
          <div className="space-y-1.5">
            <Label>Mode</Label>
            <RadioGroup
              value={mode}
              onValueChange={(v) => setMode(v as 'move' | 'copy')}
              className="grid grid-cols-2 gap-2"
            >
              <Label
                htmlFor="heap-convert-move"
                className="flex cursor-pointer items-center gap-2 rounded-md border border-border bg-surface-2 px-3 py-1.5 text-sm text-text hover:bg-surface-offset has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/15"
              >
                <RadioGroupItem id="heap-convert-move" value="move" />
                Move
              </Label>
              <Label
                htmlFor="heap-convert-copy"
                className="flex cursor-pointer items-center gap-2 rounded-md border border-border bg-surface-2 px-3 py-1.5 text-sm text-text hover:bg-surface-offset has-[[data-state=checked]]:border-primary has-[[data-state=checked]]:bg-primary/15"
              >
                <RadioGroupItem id="heap-convert-copy" value="copy" />
                Copy
              </Label>
            </RadioGroup>
            <p className="text-xs text-text-faint">
              {mode === 'move'
                ? 'Files are moved on disk; original photos update their folder.'
                : 'Files are copied on disk; new photo records are created.'}
            </p>
          </div>

          {/* Delete heap */}
          <div className="flex items-center gap-2">
            <Checkbox
              id="delete-heap"
              checked={deleteHeap}
              onCheckedChange={(v) => setDeleteHeap(v === true)}
            />
            <Label htmlFor="delete-heap" className="text-sm text-text">
              Delete heap after conversion
            </Label>
          </div>

          {convertMutation.isError && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                {(convertMutation.error as any)?.message || 'Conversion failed'}
              </AlertDescription>
            </Alert>
          )}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={onClose}
            disabled={convertMutation.isPending}
          >
            Cancel
          </Button>
          <Button
            onClick={() => convertMutation.mutate()}
            disabled={!targetId || convertMutation.isPending}
          >
            {convertMutation.isPending ? 'Converting…' : 'Convert'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
