'use client';

import React, { useState } from 'react';
import { Palette, Trash2, Save } from 'lucide-react';
import { StyleConfig } from '@/types';
import { cn } from '@/utils';
import { Button } from "@/components/ui/button";
import { ViewDisplayControl } from '@/components/common/ViewDisplayControl';
import { CreateItemControl } from '@/components/common/CreateItemControl';
import { MediaCard } from '@/components/common/MediaCard';
import { SecureImage } from '@/components/common/SecureImage';
import { useModelStore } from '@lib/store/modelStore';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { InputControl, TextareaControl, SelectControl, IconSelectControl, ModelSelectControl } from '@/components/canvas/panels/shared/FormControls';
import { useStyles, useCreateStyle, useUpdateStyle, useDeleteStyle } from '@lib/hooks/useConfig';
import { EmptyState } from '@/components/ui/empty-state';
import { LoadingState } from '@/components/ui/loading-state';
import { SearchInput } from '@/components/ui/search-input';
import { useConfirm } from '@/components/ui/confirm-dialog';

export const StylesTab: React.FC = () => {
  const { imageModels } = useModelStore();
  const { data: stylesData, isLoading: loading } = useStyles();
  const styles: StyleConfig[] = stylesData?.styles || [];
  
  const createStyleMutation = useCreateStyle();
  const updateStyleMutation = useUpdateStyle();
  const deleteStyleMutation = useDeleteStyle();

  const [searchQuery, setSearchQuery] = useState('');
  const [activeTab, setActiveTab] = useState<'all' | 'prompt' | 'lora'>('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [gridCols, setGridCols] = useState<number>(4);
  const [listCols, setListCols] = useState<number>(1);
  const currentCols = viewMode === 'grid' ? gridCols : listCols;
  
  // Editor State
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingStyle, setEditingStyle] = useState<Partial<StyleConfig> | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  // Confirm Dialog
  const { confirm, ConfirmDialog } = useConfirm();

  const getRandomGradient = () => {
    const colors = ['pink', 'blue', 'gray', 'orange', 'yellow', 'purple', 'slate', 'emerald', 'teal', 'amber', 'red', 'green', 'indigo'];
    const intensity = 500;
    const opacity = 20;
    
    const color1 = colors[Math.floor(Math.random() * colors.length)];
    const color2 = colors[Math.floor(Math.random() * colors.length)];
    
    return `from-${color1}-${intensity}/${opacity} to-${color2}-${intensity}/${opacity}`;
  };

  const handleCreate = () => {
    setEditingStyle({
      name: '',
      desc: '',
      type: 'prompt',
      prompt: '',
      lora: { id: '', base_model: '', trigger_word: '' },
      color: getRandomGradient()
    });
    setIsDialogOpen(true);
  };

  const handleEdit = (style: StyleConfig) => {
    setEditingStyle({ ...style });
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    if (editingStyle) {
      // Basic Validation
      if (!editingStyle.name?.trim()) {
        confirm({
          title: '验证失败',
          description: '风格名称不能为空',
          confirmText: '确定',
          variant: 'destructive',
          onConfirm: () => {}
        });
        return;
      }

      if (editingStyle.type === 'prompt' && !editingStyle.prompt?.trim()) {
        confirm({
            title: '验证失败',
            description: '提示词内容不能为空',
            confirmText: '确定',
            variant: 'destructive',
            onConfirm: () => {}
        });
        return;
      }

      if (editingStyle.type === 'lora') {
        if (!editingStyle.lora?.id?.trim()) {
           confirm({
            title: '验证失败',
            description: 'LoRA ID 不能为空',
            confirmText: '确定',
            variant: 'destructive',
            onConfirm: () => {}
          });
          return;
        }
        if (!editingStyle.lora?.base_model) {
            confirm({
             title: '验证失败',
             description: '请选择一个基础模型',
             confirmText: '确定',
             variant: 'destructive',
             onConfirm: () => {}
           });
           return;
         }
      }

      try {
        setIsSaving(true);
        if (editingStyle.id) {
          // Update
          await updateStyleMutation.mutateAsync({ id: editingStyle.id, data: editingStyle });
        } else {
          // Create
          await createStyleMutation.mutateAsync(editingStyle);
        }
        setIsDialogOpen(false);
      } catch (error) {
        console.error("Failed to save style:", error);
        confirm({
          title: '保存失败',
          description: error instanceof Error ? error.message : "未知错误，请检查网络连接",
          confirmText: '确定',
          variant: 'destructive',
          onConfirm: () => {}
        });
      } finally {
        setIsSaving(false);
      }
    }
  };

  const handleDialogClose = () => {
    setIsDialogOpen(false);
  };

  const handleDelete = async (id: string) => {
    confirm({
      title: '确认删除？',
      description: '确定要删除这个风格吗？此操作无法撤销。',
      variant: 'destructive',
      onConfirm: async () => {
        try {
          await deleteStyleMutation.mutateAsync(id);
          setIsDialogOpen(false);
        } catch (error) {
          console.error("Failed to delete style:", error);
        }
      }
    });
  };

  const filteredStyles = styles.filter(s => {
    const matchesSearch = s.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
      s.desc.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesTab = activeTab === 'all' || s.type === activeTab;
    return matchesSearch && matchesTab;
  });

  return (
    <div className="flex flex-col h-full bg-background text-foreground">
      <div className="flex flex-col space-y-4 mb-6 flex-shrink-0">
        <div className="flex items-center justify-between">
            <h3 className="text-lg font-medium">美术风格管理</h3>
            <SearchInput
              value={searchQuery}
              onChange={setSearchQuery}
              placeholder="搜索风格..."
              className="w-64"
            />
        </div>

        <div className="flex items-center justify-between">
          {/* Tabs */}
          <div className="flex space-x-1 bg-muted/20 p-1 rounded-lg border border-border w-fit">
              {[
                { id: 'all', label: '全部' },
                { id: 'prompt', label: 'Prompt' },
                { id: 'lora', label: 'LoRA' }
              ].map((tab) => (
                  <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id as any)}
                      className={cn(
                          "flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-medium transition-all",
                          activeTab === tab.id
                              ? "bg-background text-foreground shadow-sm border border-border/50"
                              : "text-muted-foreground hover:text-foreground hover:bg-background/50"
                      )}
                  >
                      <span>{tab.label}</span>
                  </button>
              ))}
          </div>

          {/* Grid Columns Control */}
          <div className="flex items-center gap-3">
            <CreateItemControl 
                label="新建风格"
                onClick={handleCreate}
            />
            <ViewDisplayControl 
                mode={viewMode}
                onModeChange={setViewMode}
                gridColumns={gridCols}
                setGridColumns={setGridCols}
                listColumns={listCols}
                setListColumns={setListCols}
            />
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto min-h-0 pr-2">
          {loading ? (
            <LoadingState message="加载风格中..." />
          ) : (
          <div className={cn(
              "grid gap-4 pb-6",
              // Grid Mode Classes
              viewMode === 'grid' && currentCols === 2 && "grid-cols-2",
              viewMode === 'grid' && currentCols === 3 && "grid-cols-3",
              viewMode === 'grid' && currentCols === 4 && "grid-cols-4",
              viewMode === 'grid' && currentCols === 5 && "grid-cols-5",
              viewMode === 'grid' && currentCols === 6 && "grid-cols-6",
              // List Mode Classes
              viewMode === 'list' && currentCols === 1 && "grid-cols-1",
              viewMode === 'list' && currentCols === 2 && "grid-cols-2"
          )}>
          
          {filteredStyles.map((style) => (
              <MediaCard
                  key={style.id}
                  layoutMode={viewMode}
                  onSelect={() => handleEdit(style)}
                  className={viewMode === 'grid' ? "aspect-video" : "h-auto min-h-[120px]"}
                  mediaClassName={viewMode === 'list' ? "w-[120px]" : ""}
                  media={
                      style.imageUrl ? (
                          <SecureImage 
                              src={style.imageUrl} 
                              alt={style.name} 
                              className="w-full h-full object-cover"
                          />
                      ) : (
                          <div className={`w-full h-full bg-gradient-to-br ${style.color || 'from-gray-800 to-gray-900'}`} />
                      )
                  }
                  title={style.name}
              titleClassName="text-base mb-1"
          >
              <>
                  <div className="flex flex-wrap gap-1 mb-2">
                              <span className="text-[10px] bg-white/10 text-foreground/80 px-1.5 py-0.5 rounded backdrop-blur-sm">
                                  {style.type === 'lora' ? 'LoRA' : 'Prompt'}
                              </span>
                          </div>
                          
                          <p className={cn(
                              "text-xs text-foreground/60 line-clamp-1",
                              viewMode === 'grid' ? "mb-2" : "mb-0"
                          )}>
                              {style.desc}
                          </p>
                      </>
          </MediaCard>
          ))}
          
          {filteredStyles.length === 0 && (
            <EmptyState 
              icon={Palette}
              title="没有找到相关风格"
              description="尝试调整搜索条件或创建新风格"
              className="col-span-full h-64"
            />
          )}
        </div>
      )}
      </div>

      {/* Edit Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="text-xl">
              {editingStyle?.id ? "编辑风格" : "新建风格"}
            </DialogTitle>
            <p className="text-sm text-muted-foreground mt-1">
              {editingStyle?.id ? "修改美术风格配置" : "创建新的美术风格预设"}
            </p>
          </DialogHeader>

          {editingStyle && (
            <div className="flex-1 overflow-y-auto pr-2 py-4">
              <div className="space-y-4">
                {/* 基本信息 */}
                <InputControl 
                  label="风格名称" 
                  value={editingStyle.name || ''} 
                  onChange={(val) => setEditingStyle({...editingStyle, name: val})}
                  placeholder="例如：赛博朋克、水彩画风..."
                  required
                />
                <TextareaControl 
                  label="风格描述" 
                  value={editingStyle.desc || ''} 
                  onChange={(val) => setEditingStyle({...editingStyle, desc: val})}
                  rows={2}
                  placeholder="简要描述该风格的视觉特点和适用场景..."
                />
                <SelectControl
                  label="风格类型"
                  value={editingStyle.type || 'prompt'}
                  options={[
                    { label: '纯提示词 (Prompt) - 通过文本描述实现风格', value: 'prompt' },
                    { label: 'LoRA 模型 - 使用训练好的风格模型', value: 'lora' }
                  ]}
                  onChange={(val) => setEditingStyle({...editingStyle, type: val as any})}
                />

                {/* Prompt Config */}
                {editingStyle.type === 'prompt' && (
                  <>
                    <TextareaControl
                      label="风格提示词 (PROMPT)"
                      value={editingStyle.prompt || ''}
                      onChange={(val) => setEditingStyle({...editingStyle, prompt: val})}
                      rows={5}
                      placeholder="输入该风格的核心提示词，例如：&#10;cyberpunk style, neon lights, high contrast, futuristic buildings, mechanical modifications"
                    />
                    <p className="text-xs text-muted-foreground -mt-2">
                      💡 提示：使用英文逗号分隔多个关键词，越靠前的词权重越高
                    </p>
                  </>
                )}

                {/* LoRA Config */}
                {editingStyle.type === 'lora' && (
                  <>
                    <InputControl 
                      label="LoRA ID" 
                      value={editingStyle.lora?.id || ''} 
                      onChange={(val) => setEditingStyle({
                        ...editingStyle, 
                        lora: { ...editingStyle.lora!, id: val }
                      })}
                      placeholder="例如: fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA"
                      required
                    />
                    <p className="text-xs text-muted-foreground -mt-2">
                      从 HuggingFace 或 Civitai 获取的 LoRA 模型标识符
                    </p>
                    
                    <ModelSelectControl 
                      label="基础模型" 
                      value={editingStyle.lora?.base_model || ''} 
                      models={Object.values(imageModels)
                        .filter(m => m.capabilities?.supportsLora)
                      }
                      onChange={(val) => setEditingStyle({
                        ...editingStyle, 
                        lora: { ...editingStyle.lora!, base_model: val }
                      })}
                      required
                    />
                    <p className="text-xs text-muted-foreground -mt-2">
                      选择与 LoRA 兼容的基础图像生成模型
                    </p>
                    
                    <InputControl 
                      label="触发词" 
                      value={editingStyle.lora?.trigger_word || ''} 
                      onChange={(val) => setEditingStyle({
                        ...editingStyle, 
                        lora: { ...editingStyle.lora!, trigger_word: val }
                      })}
                      placeholder="例如: sks, style_name (可选)"
                    />
                    <p className="text-xs text-muted-foreground -mt-2">
                      某些 LoRA 需要特定触发词才能激活风格效果
                    </p>
                  </>
                )}
              </div>
            </div>
          )}

          {/* Footer Actions */}
          <div className="flex items-center justify-between pt-4 border-t border-border mt-4">
            {editingStyle?.id ? (
              <Button 
                variant="ghost"
                onClick={() => handleDelete(editingStyle.id!)}
                className="flex items-center gap-2 text-red-500 hover:text-red-600 hover:bg-red-500/10"
              >
                <Trash2 size={16} />
                <span>删除风格</span>
              </Button>
            ) : (
              <div />
            )}
            
            <div className="flex items-center gap-3">
              <Button 
                variant="outline"
                onClick={handleDialogClose}
                className="h-10 px-6"
                disabled={isSaving}
              >
                取消
              </Button>
              <Button 
                onClick={handleSave}
                className="bg-primary hover:bg-primary/90 h-10 px-6"
                disabled={isSaving}
              >
                {isSaving ? (
                    <span className="flex items-center gap-2">
                        <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                        保存中...
                    </span>
                ) : (
                    <>
                        <Save size={16} className="mr-2" />
                        保存
                    </>
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Confirm Dialog */}
      <ConfirmDialog />
    </div>
  );
};
