import {
  useCreateStandard,
  useDeleteStandard,
  useStandards,
  useUpdateStandard,
} from '@/entity/element/model/implementations/StandardsElement/hooks'
import {
  CreateStandardInput,
  PatchStandardInput,
  Standard,
} from '@/entity/element/model/implementations/StandardsElement/types'
import {
  Calendar,
  Edit,
  FileText,
  Gauge,
  Plus,
  Search,
  Trash2,
  Weight,
} from 'lucide-react'
import { useEffect, useState } from 'react'
import { Badge } from 'shared/ui/badge'
import { Button } from 'shared/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from 'shared/ui/dialog'
import { Input } from 'shared/ui/input'
import { Label } from 'shared/ui/label'

export const StandardsManagementPage = () => {
  const [searchTerm, setSearchTerm] = useState('')
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [editingStandard, setEditingStandard] = useState<Standard | null>(null)
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)

  const { data: standards = [], isLoading, error } = useStandards()
  const createMutation = useCreateStandard()
  const updateMutation = useUpdateStandard()
  const deleteMutation = useDeleteStandard()

  // Фильтрация эталонов
  const filteredStandards = standards.filter(
    standard =>
      standard.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      standard.protocol_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      standard.registry_number.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const handleCreate = (input: CreateStandardInput) => {
    createMutation.mutate(input, {
      onSuccess: () => {
        setIsCreateDialogOpen(false)
      },
    })
  }

  const handleUpdate = (id: string, input: PatchStandardInput) => {
    updateMutation.mutate(
      { id, input },
      {
        onSuccess: () => {
          setEditingStandard(null)
        },
      }
    )
  }

  const handleDelete = (id: string) => {
    deleteMutation.mutate(id, {
      onSuccess: () => {
        setDeleteConfirmId(null)
      },
    })
  }

  if (isLoading) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-center">
          <div className="mx-auto mb-2 h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
          <p className="text-muted-foreground">Загрузка эталонов...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-center">
          <p className="mb-2 text-destructive">Ошибка загрузки эталонов</p>
          <p className="text-sm text-muted-foreground">{error.message}</p>
        </div>
      </div>
    )
  }

  return (
    <div className="flex h-screen flex-col">
      {/* Заголовок страницы */}
      <header className="flex-shrink-0 border-b bg-card px-4 py-2">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Weight className="h-5 w-5" />
            <h1 className="text-lg font-semibold">Управление эталонами</h1>
            <span className="text-sm text-muted-foreground">—</span>
            <span className="text-sm text-muted-foreground">
              Всего эталонов: {standards.length}
            </span>
          </div>
          <Button onClick={() => setIsCreateDialogOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Создать эталон
          </Button>
        </div>
      </header>

      {/* Основное содержимое */}
      <main className="flex-1 overflow-auto p-6">
        <div className="space-y-6">
          {/* Поиск */}
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Поиск эталонов..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          {/* Список эталонов */}
          {filteredStandards.length > 0 ? (
            <section className="space-y-2">
              {filteredStandards.map(standard => (
                <StandardCard
                  key={standard.id}
                  standard={standard}
                  onEdit={() => setEditingStandard(standard)}
                  onDelete={() => setDeleteConfirmId(standard.id)}
                />
              ))}
            </section>
          ) : (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <div className="text-muted-foreground">
                <Weight className="mx-auto mb-4 h-12 w-12 opacity-50" />
                <p className="text-lg font-medium">
                  {searchTerm ? 'Эталоны не найдены' : 'Эталоны не созданы'}
                </p>
                <p className="text-sm">
                  {searchTerm
                    ? `Попробуйте изменить поисковый запрос "${searchTerm}"`
                    : 'Создайте свой первый эталон для начала работы'}
                </p>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* Диалоги */}
      <StandardDialog
        isOpen={isCreateDialogOpen}
        onClose={() => setIsCreateDialogOpen(false)}
        onSave={handleCreate}
        isLoading={createMutation.isPending}
        title="Создать эталон"
      />

      <StandardDialog
        isOpen={!!editingStandard}
        onClose={() => setEditingStandard(null)}
        onSave={input =>
          editingStandard && handleUpdate(editingStandard.id, input)
        }
        isLoading={updateMutation.isPending}
        title="Редактировать эталон"
        initialData={editingStandard || undefined}
      />

      <DeleteConfirmDialog
        isOpen={!!deleteConfirmId}
        onClose={() => setDeleteConfirmId(null)}
        onConfirm={() => deleteConfirmId && handleDelete(deleteConfirmId)}
        isLoading={deleteMutation.isPending}
        standardName={standards.find(s => s.id === deleteConfirmId)?.name || ''}
      />
    </div>
  )
}

// Компонент карточки эталона
interface StandardCardProps {
  standard: Standard
  onEdit: () => void
  onDelete: () => void
}

const StandardCard = ({ standard, onEdit, onDelete }: StandardCardProps) => {
  const isExpiringSoon = () => {
    const expiryDate = new Date(standard.valid_until)
    const now = new Date()
    const monthsUntilExpiry =
      (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30)
    return monthsUntilExpiry <= 3
  }

  return (
    <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-3 transition-all duration-200 hover:border-primary/50 hover:bg-primary/5">
      {/* Основная информация */}
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-3">
          <div className="min-w-20 shrink-0 text-sm font-medium text-foreground">
            {standard.protocol_name}
          </div>
          <div className="truncate text-sm text-muted-foreground">
            {standard.name}
          </div>
          {isExpiringSoon() && (
            <Badge variant="destructive" className="shrink-0 text-xs">
              <Calendar className="mr-1 h-3 w-3" />
              Истекает
            </Badge>
          )}
        </div>
      </div>

      {/* Дополнительная информация */}
      <div className="flex shrink-0 items-center gap-4 text-xs text-muted-foreground">
        <div className="flex items-center gap-1">
          <FileText className="h-3 w-3" />
          <span className="hidden sm:inline">{standard.registry_number}</span>
        </div>
        <Badge variant="secondary" className="px-1.5 py-0.5 text-xs">
          {standard.range}
        </Badge>
        <div className="hidden items-center gap-1 md:flex">
          <Gauge className="h-3 w-3" />
          <span>{standard.accuracy}</span>
        </div>
      </div>

      {/* Действия */}
      <div className="flex shrink-0 gap-1">
        <Button
          variant="ghost"
          size="sm"
          className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
          onClick={onEdit}
        >
          <Edit className="h-4 w-4" />
        </Button>
        <Button
          variant="ghost"
          size="sm"
          className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
          onClick={onDelete}
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>
    </div>
  )
}

// Диалог создания/редактирования эталона
interface StandardDialogProps {
  isOpen: boolean
  onClose: () => void
  onSave: (input: CreateStandardInput) => void
  isLoading: boolean
  title: string
  initialData?: Standard
}

const StandardDialog = ({
  isOpen,
  onClose,
  onSave,
  isLoading,
  title,
  initialData,
}: StandardDialogProps) => {
  const [formData, setFormData] = useState<CreateStandardInput>({
    name: initialData?.name || '',
    protocol_name: initialData?.protocol_name || '',
    registry_number: initialData?.registry_number || '',
    range: initialData?.range || '',
    accuracy: initialData?.accuracy || '',
    valid_until: initialData?.valid_until || '',
  })

  // Обновляем formData при изменении initialData
  useEffect(() => {
    if (initialData) {
      setFormData({
        name: initialData.name || '',
        protocol_name: initialData.protocol_name || '',
        registry_number: initialData.registry_number || '',
        range: initialData.range || '',
        accuracy: initialData.accuracy || '',
        valid_until: initialData.valid_until || '',
      })
    }
  }, [initialData])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSave(formData)
  }

  const handleClose = () => {
    if (!initialData) {
      setFormData({
        name: '',
        protocol_name: '',
        registry_number: '',
        range: '',
        accuracy: '',
        valid_until: '',
      })
    }
    onClose()
  }

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="name">Название</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={e =>
                setFormData(prev => ({ ...prev, name: e.target.value }))
              }
              placeholder="Эталон массы 1 кг"
              required
            />
          </div>

          <div>
            <Label htmlFor="protocol_name">Протокольное название</Label>
            <Input
              id="protocol_name"
              value={formData.protocol_name}
              onChange={e =>
                setFormData(prev => ({
                  ...prev,
                  protocol_name: e.target.value,
                }))
              }
              placeholder="ЭМ-1кг"
              required
            />
          </div>

          <div>
            <Label htmlFor="registry_number">Номер в реестре</Label>
            <Input
              id="registry_number"
              value={formData.registry_number}
              onChange={e =>
                setFormData(prev => ({
                  ...prev,
                  registry_number: e.target.value,
                }))
              }
              placeholder="ГРСИ 12345-01"
              required
            />
          </div>

          <div>
            <Label htmlFor="range">Диапазон</Label>
            <Input
              id="range"
              value={formData.range}
              onChange={e =>
                setFormData(prev => ({ ...prev, range: e.target.value }))
              }
              placeholder="0.5-2 кг"
              required
            />
          </div>

          <div>
            <Label htmlFor="accuracy">Точность</Label>
            <Input
              id="accuracy"
              value={formData.accuracy}
              onChange={e =>
                setFormData(prev => ({ ...prev, accuracy: e.target.value }))
              }
              placeholder="±0.001 г"
              required
            />
          </div>

          <div>
            <Label htmlFor="valid_until">Действует до</Label>
            <Input
              id="valid_until"
              type="date"
              value={formData.valid_until}
              onChange={e =>
                setFormData(prev => ({ ...prev, valid_until: e.target.value }))
              }
              required
            />
          </div>

          <div className="flex justify-end gap-2 pt-4">
            <Button type="button" variant="outline" onClick={handleClose}>
              Отмена
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? 'Сохранение...' : 'Сохранить'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}

// Диалог подтверждения удаления
interface DeleteConfirmDialogProps {
  isOpen: boolean
  onClose: () => void
  onConfirm: () => void
  isLoading: boolean
  standardName: string
}

const DeleteConfirmDialog = ({
  isOpen,
  onClose,
  onConfirm,
  isLoading,
  standardName,
}: DeleteConfirmDialogProps) => {
  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Удалить эталон?</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <p className="text-muted-foreground">
            Вы действительно хотите удалить эталон{' '}
            <strong>{standardName}</strong>?
          </p>
          <p className="text-sm text-muted-foreground">
            Это действие нельзя отменить.
          </p>

          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={onClose}>
              Отмена
            </Button>
            <Button
              variant="destructive"
              onClick={onConfirm}
              disabled={isLoading}
            >
              {isLoading ? 'Удаление...' : 'Удалить'}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
