'use client'

import { useRef, useState, useTransition } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
  useDirtyCloseGuard,
  DirtyCloseGuardDialog,
} from '@/components/shared/use-dirty-close-guard'
import { useDialogSubmitShortcut } from '@/components/shared/use-dialog-submit-shortcut'
import {
  entityDialogContentClasses,
  entityDialogFooterClasses,
  entityDialogHeaderClasses,
} from '@/components/shared/entity-dialog-layout'
import { useUserSettingsStore } from '@/stores/user-settings/store'
import { debugProps } from '@/lib/debug'

interface NewSprintMetadataDialogProps {
  open: boolean
  productId: string
  onOpenChange: (open: boolean) => void
}

function todayLocalDate(): string {
  return new Date().toLocaleDateString('en-CA')
}

function plusWeeks(weeks: number): string {
  const d = new Date()
  d.setDate(d.getDate() + weeks * 7)
  return d.toLocaleDateString('en-CA')
}

export function NewSprintMetadataDialog({
  open,
  productId,
  onOpenChange,
}: NewSprintMetadataDialogProps) {
  const [sprintGoal, setSprintGoal] = useState('')
  const [startDate, setStartDate] = useState(todayLocalDate())
  const [endDate, setEndDate] = useState(plusWeeks(2))
  const [error, setError] = useState<string | null>(null)
  const [dirty, setDirty] = useState(false)
  const [isPending, startTransition] = useTransition()
  const formRef = useRef<HTMLFormElement>(null)
  const setPendingSprintDraft = useUserSettingsStore(
    (s) => s.setPendingSprintDraft,
  )

  function reset() {
    setSprintGoal('')
    setStartDate(todayLocalDate())
    setEndDate(plusWeeks(2))
    setError(null)
    setDirty(false)
  }

  const closeGuard = useDirtyCloseGuard(dirty, () => {
    onOpenChange(false)
    reset()
  })

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const goal = sprintGoal.trim()
    if (!goal) return
    setError(null)
    startTransition(async () => {
      try {
        await setPendingSprintDraft(productId, {
          goal,
          startAt: startDate || undefined,
          endAt: endDate || undefined,
          pbiIntent: {},
          storyOverrides: {},
        })
        reset()
        onOpenChange(false)
      } catch (err) {
        const message =
          err instanceof Error ? err.message : 'Onbekende fout bij opslaan'
        setError(message)
        toast.error(message)
      }
    })
  }

  const handleKeyDown = useDialogSubmitShortcut(() =>
    formRef.current?.requestSubmit(),
  )

  return (
    <>
      <Dialog
        open={open}
        onOpenChange={(o) => {
          if (!o) closeGuard.attemptClose()
          else onOpenChange(o)
        }}
      >
        <DialogContent
          showCloseButton={false}
          onKeyDown={handleKeyDown}
          className={entityDialogContentClasses}
          {...debugProps(
            'new-sprint-metadata-dialog',
            'NewSprintMetadataDialog',
            'components/backlog/new-sprint-metadata-dialog.tsx',
          )}
        >
          <div className={entityDialogHeaderClasses}>
            <DialogTitle className="text-xl font-semibold">
              Nieuwe sprint
            </DialogTitle>
            <p className="text-xs text-muted-foreground mt-1">
              Geef het sprint-doel en periode op. Je selecteert daarna PBI&apos;s
              en stories via vinkjes in de backlog.
            </p>
          </div>

          <form
            ref={formRef}
            id="new-sprint-metadata-form"
            onSubmit={handleSubmit}
            onChange={() => setDirty(true)}
            className="flex-1 overflow-y-auto px-6 py-6 space-y-6"
          >
            <div className="space-y-1.5">
              <label className="text-sm font-medium text-foreground">
                Sprint Goal <span className="text-error">*</span>
              </label>
              <Textarea
                value={sprintGoal}
                onChange={(e) => setSprintGoal(e.target.value)}
                required
                rows={3}
                placeholder="Wat wil je aan het einde van deze Sprint bereikt hebben?"
                autoFocus
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-foreground">
                  Startdatum
                </label>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="w-full rounded-md border border-border bg-surface-container px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium text-foreground">
                  Einddatum
                </label>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="w-full rounded-md border border-border bg-surface-container px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
                />
              </div>
            </div>

            {error && (
              <div className="bg-error-container text-error-container-foreground rounded-lg px-3 py-2 text-sm border-l-4 border-error">
                {error}
              </div>
            )}
          </form>

          <div className={entityDialogFooterClasses}>
            <div className="flex justify-end gap-2">
              <Button
                type="button"
                variant="ghost"
                onClick={closeGuard.attemptClose}
                disabled={isPending}
              >
                Annuleren
              </Button>
              <Button
                type="submit"
                form="new-sprint-metadata-form"
                disabled={isPending || !sprintGoal.trim()}
                data-debug-id="new-sprint-metadata-dialog__submit"
              >
                {isPending ? 'Opslaan…' : 'Verder'}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <DirtyCloseGuardDialog guard={closeGuard} />
    </>
  )
}
