import { useGroupContext } from '@/entity/group/model/GroupContext'
import { Group } from '@/type/template'
import { Edit3, FolderPlus, Plus, Tag } from 'lucide-react'
import { useState } from 'react'
import { Button } from 'shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from 'shared/ui/card'
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from 'shared/ui/dialog'
import { Input } from 'shared/ui/input'
import { Label } from 'shared/ui/label'
import { Separator } from 'shared/ui/separator'

interface GroupFormProps {
  title: string
  description: string
  icon: React.ReactNode
  group?: Group
  onSubmit: (name: string) => void | Promise<void>
  onCancel: () => void
  submitText: string
  submitIcon: React.ReactNode
}

const GroupForm: React.FC<GroupFormProps> = ({
  title,
  description,
  icon,
  group,
  onSubmit,
  onCancel,
  submitText,
  submitIcon,
}) => {
  const [name, setName] = useState(group?.name || '')

  const handleSubmit = () => {
    if (name.trim()) {
      onSubmit(name.trim())
    }
  }

  return (
    <>
      <DialogHeader className="pb-4">
        <DialogTitle className="flex items-center gap-2 text-lg">
          {icon}
          {title}
        </DialogTitle>
        <DialogDescription>{description}</DialogDescription>
      </DialogHeader>

      <div className="space-y-4">
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center gap-2">
              <Tag className="h-4 w-4 text-blue-600" />
              <CardTitle className="text-sm">Название группы</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="group-name">Название</Label>
              <Input
                id="group-name"
                placeholder="Введите название группы"
                value={name}
                onChange={e => setName(e.target.value)}
                className="h-9"
              />
            </div>
          </CardContent>
        </Card>
      </div>

      <Separator className="my-4" />
      <div className="flex items-center justify-between pt-2">
        <div className="text-sm text-muted-foreground">
          {!name.trim() && (
            <span className="text-amber-600">Заполните название группы</span>
          )}
        </div>
        <div className="flex gap-3">
          <DialogClose asChild>
            <Button variant="outline">Отмена</Button>
          </DialogClose>
          <Button
            onClick={handleSubmit}
            disabled={!name.trim()}
            className="min-w-[130px]"
          >
            {submitIcon}
            {submitText}
          </Button>
        </div>
      </div>
    </>
  )
}

interface GroupManagerProps {
  onGroupCreated?: (groupId: string) => void
  editingGroupId?: string | null
  onEditingGroupChange?: (groupId: string | null) => void
}

export const GroupManager: React.FC<GroupManagerProps> = ({
  onGroupCreated,
  editingGroupId,
  onEditingGroupChange,
}) => {
  const { groups, addGroup, updateGroup } = useGroupContext()
  const [isCreateOpen, setIsCreateOpen] = useState(false)
  
  // Получаем группу для редактирования из пропсов
  const editingGroup = editingGroupId ? groups.find(g => g.id === editingGroupId) || null : null

  const handleCreate = async (name: string) => {
    try {
      const newGroup = await addGroup({ name })
      setIsCreateOpen(false)
      onGroupCreated?.(newGroup.id)
    } catch (error) {
      console.error('Ошибка при создании группы:', error)
    }
  }

  const handleEdit = async (name: string) => {
    if (editingGroup) {
      try {
        await updateGroup(editingGroup.id, { name })
        onEditingGroupChange?.(null)
      } catch (error) {
        console.error('Ошибка при редактировании группы:', error)
      }
    }
  }

  const handleCancelEdit = () => {
    onEditingGroupChange?.(null)
  }

  return (
    <>
      {/* Кнопка создания новой группы */}
      <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
        <DialogTrigger asChild>
          <Button size="sm" variant="outline">
            <FolderPlus className="mr-1 h-4 w-4" />
            Новая группа
          </Button>
        </DialogTrigger>
        <DialogContent className="max-h-[90vh] max-w-2xl overflow-hidden">
          <GroupForm
            title="Создать новую группу"
            description="Создайте группу для организации ваших шаблонов"
            icon={<FolderPlus className="h-5 w-5 text-blue-600" />}
            onSubmit={handleCreate}
            onCancel={() => setIsCreateOpen(false)}
            submitText="Создать"
            submitIcon={<Plus className="mr-2 h-4 w-4" />}
          />
        </DialogContent>
      </Dialog>

      {/* Диалог редактирования группы */}
      <Dialog open={!!editingGroup} onOpenChange={handleCancelEdit}>
        <DialogContent className="max-h-[90vh] max-w-2xl overflow-hidden">
          <GroupForm
            title="Редактировать группу"
            description="Измените название группы"
            icon={<Edit3 className="h-5 w-5 text-orange-600" />}
            group={editingGroup || undefined}
            onSubmit={handleEdit}
            onCancel={handleCancelEdit}
            submitText="Сохранить"
            submitIcon={<Edit3 className="mr-2 h-4 w-4" />}
          />
        </DialogContent>
      </Dialog>
    </>
  )
}

export default GroupManager