import React, { useState, useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Save } from 'lucide-react';
import { useProjectStore } from '@/lib/store/project';
import { SelectControl, ModelSelectControl } from '@components/canvas/panels/shared/FormControls';
import { useStyles, useModels, useUserApiKeys } from '@lib/hooks/useConfig';
import { useAuthStore } from '@/store/authStore';
import { Button } from '@/components/ui/button';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { DefaultService } from '@/lib/api';
import { SettingCard } from '@/components/ui/setting-card';

const PROJECT_STATUSES = [
  { label: '进行中', value: 'active' },
  { label: '草稿', value: 'draft' },
  { label: '已完成', value: 'completed' },
  { label: '归档', value: 'archived' }
];

const RESOLUTIONS = [
  '720P', '1080P', '2K', '4K'
].map(v => ({ label: v, value: v }));

const RATIOS = [
  '16:9', '9:16', '1:1', '4:3', '3:4', '21:9'
].map(v => ({ label: v, value: v }));

export const SettingsTab: React.FC = () => {
  const [saving, setSaving] = useState(false);
  const { confirm, ConfirmDialog } = useConfirm();
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);

  const {
    projectId,
    status,
    resolution,
    ratio,
    styleId,
    defaultImageModel,
    defaultVideoModel,
    defaultAudioModel,
    defaultLLMModel,
    updateProjectMeta,
    setProject,
  } = useProjectStore(
    useShallow((s) => ({
      projectId: s.id,
      status: s.status,
      resolution: s.resolution,
      ratio: s.ratio,
      styleId: s.styleId,
      defaultImageModel: s.defaultImageModel,
      defaultVideoModel: s.defaultVideoModel,
      defaultAudioModel: s.defaultAudioModel,
      defaultLLMModel: s.defaultLLMModel,
      updateProjectMeta: s.updateProjectMeta,
      setProject: s.setProject,
    }))
  );

  const { data: stylesData } = useStyles();
  const styles = stylesData?.styles;

  // Load models from API
  const { data: modelsData } = useModels();
  const { data: apiKeys } = useUserApiKeys(isAuthenticated);

  // Get configured providers
  const configuredProviders = useMemo(() =>
    new Set(apiKeys?.filter(k => k.isActive).map(k => k.provider) || []),
    [apiKeys]
  );

  // Filter models to only include those with configured API keys
  const models = useMemo(() => {
    if (!modelsData) return [];

    const allModels = [
      ...Object.values(modelsData.image || {}),
      ...Object.values(modelsData.video || {}),
      ...Object.values(modelsData.audio || {}),
      ...Object.values(modelsData.llm || {}),
      ...Object.values(modelsData.lyrics || {}),
      ...Object.values(modelsData.music || {}),
    ];

    return allModels.filter((m: any) => configuredProviders.has(m.provider));
  }, [modelsData, configuredProviders]);

  const imageModels = models.filter((m: any) => m.type === 'image' || m.type === 'image_generation');
  const videoModels = models.filter((m: any) => m.type === 'video' || m.type === 'video_generation');
  const audioModels = models.filter((m: any) => m.type === 'audio' || m.type === 'audio_generation');
  const llmModels = models.filter((m: any) => m.type === 'llm' || m.type === 'text_generation');
  
  const styleOptions = React.useMemo(() => {
    const baseOptions = [{ label: '不使用', value: 'none' }];
    const validStyles = (styles ?? [])
      .filter((s: any) => s && s.id && s.name)
      .map((s: any) => ({ label: s.name, value: String(s.id) }));
    
    // Deduplicate by value
    const seen = new Set(['none']);
    const uniqueStyles: { label: string; value: string }[] = [];
    
    validStyles.forEach((opt: { label: string; value: string }) => {
      if (!seen.has(opt.value)) {
        seen.add(opt.value);
        uniqueStyles.push(opt);
      }
    });
    
    return [...baseOptions, ...uniqueStyles];
  }, [styles]);
  
  // Save project settings
  const handleSave = async () => {
    if (!projectId) {
      confirm({
        title: '错误',
        description: '项目 ID 不存在',
        confirmText: '确定',
        variant: 'destructive',
        onConfirm: () => {}
      });
      return;
    }
    
    setSaving(true);
    try {
      const updateData = {
        resolution: resolution ?? undefined,
        ratio: ratio ?? undefined,
        styleId: styleId === 'none' ? undefined : styleId,
        // 以下字段若后端 schema 未声明会被忽略，保留以便后端扩展后生效
        ...(status && { status }),
        ...(defaultImageModel != null && { defaultImageModel }),
        ...(defaultVideoModel != null && { defaultVideoModel }),
        ...(defaultAudioModel != null && { defaultAudioModel }),
        ...(defaultLLMModel != null && { defaultLLMModel }),
      };
      const res = await DefaultService.updateProject(projectId, updateData);
      if (res.data) {
        setProject(res.data);
      }
      
      confirm({
        title: '保存成功',
        description: '项目设置已更新',
        confirmText: '确定',
        onConfirm: () => {}
      });
    } catch (error) {
      console.error('Failed to save project settings:', error);
      confirm({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        confirmText: '确定',
        variant: 'destructive',
        onConfirm: () => {}
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <ConfirmDialog />
      <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
        
        {/* Header */}
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium">项目设置</h3>
          <Button 
            onClick={handleSave} 
            disabled={saving}
            className="bg-primary hover:bg-primary/90"
          >
            <Save className="w-4 h-4 mr-2" />
            {saving ? '保存中...' : '保存设置'}
          </Button>
        </div>
      
      {/* 基础信息 */}
      <SettingCard
        title="基础信息"
        description="项目的基本信息设置"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <SelectControl
            label="项目状态"
            value={status}
            options={PROJECT_STATUSES}
            onChange={(v) => updateProjectMeta({ status: v })}
          />
        </div>
      </SettingCard>

      {/* 画面规格 */}
      <SettingCard
        title="画面规格"
        description="设置项目的视频输出规格"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <SelectControl 
            label="分辨率"
            value={resolution || '1080P'}
            options={RESOLUTIONS}
            onChange={(v) => updateProjectMeta({ resolution: v })}
          />
          <SelectControl 
            label="画面比例"
            value={ratio || '16:9'}
            options={RATIOS}
            onChange={(v) => updateProjectMeta({ ratio: v })}
          />
        </div>
      </SettingCard>

      {/* 艺术风格 */}
      <SettingCard
        title="艺术风格"
        description="选择项目的默认画风预设"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <SelectControl 
            label="画风预设"
            value={styleId || 'none'}
            options={styleOptions}
            onChange={(v) => updateProjectMeta({ styleId: v === 'none' ? undefined : v })}
          />
        </div>
      </SettingCard>
      
      {/* 默认模型配置 */}
      <SettingCard
        title="默认模型配置"
        description="设置此项目的默认模型，优先级高于系统设置。留空则使用系统默认模型。"
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <ModelSelectControl
            label="图像模型"
            models={imageModels}
            value={defaultImageModel || ''}
            onChange={(value) => updateProjectMeta({ defaultImageModel: value || undefined })}
            placeholder="使用系统默认"
          />

          <ModelSelectControl
            label="视频模型"
            models={videoModels}
            value={defaultVideoModel || ''}
            onChange={(value) => updateProjectMeta({ defaultVideoModel: value || undefined })}
            placeholder="使用系统默认"
          />

          <ModelSelectControl
            label="音频模型"
            models={audioModels}
            value={defaultAudioModel || ''}
            onChange={(value) => updateProjectMeta({ defaultAudioModel: value || undefined })}
            placeholder="使用系统默认"
          />

          <ModelSelectControl
            label="文本模型 (LLM)"
            models={llmModels}
            value={defaultLLMModel || ''}
            onChange={(value) => updateProjectMeta({ defaultLLMModel: value || undefined })}
            placeholder="使用系统默认"
          />
        </div>
      </SettingCard>

    </div>
    </>
  );
};
