import React, { useState, useEffect, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { FileText, Save, Delete, Pencil, PlusCircle, Loader2, Trash2, Copy } from 'lucide-react';
import { textTemplateAPI } from '@/api/textTemplates';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

const DEFAULT_TEXT_TYPES = ['prompt', 'copywrite'];
const TEXT_TYPE_LABELS = {
  prompt: '生图提示词',
  copywrite: '文案提示词',
  unknown: '未知类型'
};

export default function TextPromptManager({ initialType = 'prompt' }) {
  const { user } = useAuth();
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [message, setMessage] = useState(null);
  const [createForm, setCreateForm] = useState({
    text_type: initialType,
    text_name: '',
    text_label: '',
    text_content: ''
  });
  const [activeType, setActiveType] = useState(initialType);
  const [selectedId, setSelectedId] = useState('');
  const [editForm, setEditForm] = useState({ text_name: '', text_label: '', text_content: '' });

  useEffect(() => {
    if (user?.id) {
      loadTemplates(user.id);
    }
  }, [user]);

  useEffect(() => {
    // 切换类型时，重置创建表单的类型
    setCreateForm(prev => ({ ...prev, text_type: activeType }));
    // 切换类型后清空选择与编辑
    setSelectedId('');
    setEditForm({ text_name: '', text_label: '', text_content: '' });
  }, [activeType]);

  const loadTemplates = async (userId) => {
    setIsLoading(true);
    try {
      const resp = await textTemplateAPI.getTextTemplates(userId);
      if (resp.success) {
        setTemplates(resp.templates || []);
      } else {
        toast.error(resp.error || '加载文本模板失败');
      }
    } catch (e) {
      toast.error('加载文本模板失败');
    } finally {
      setIsLoading(false);
    }
  };

  const groupedTemplates = useMemo(() => {
    const map = new Map();
    const allTypes = new Set(DEFAULT_TEXT_TYPES);
    for (const t of templates) {
      allTypes.add(t.text_type || 'unknown');
    }
    for (const type of allTypes) map.set(type, []);
    for (const t of templates) {
      const key = t.text_type || 'unknown';
      map.get(key).push(t);
    }
    return map;
  }, [templates]);

  const currentList = useMemo(() => groupedTemplates.get(activeType) || [], [groupedTemplates, activeType]);

  const onSelectTemplate = (id) => {
    setSelectedId(id);
    const found = currentList.find(t => String(t.id) === String(id));
    if (found) {
      setEditForm({
        text_name: found.text_name || '',
        text_label: found.text_label || '',
        text_content: found.text_content || ''
      });
    } else {
      setEditForm({ text_name: '', text_label: '', text_content: '' });
    }
  };

  const handleSaveEdit = async () => {
    if (!user?.id || !selectedId) return;
    try {
      const resp = await textTemplateAPI.updateTextTemplate(user.id, selectedId, {
        textType: activeType,
        textName: editForm.text_name,
        textLabel: editForm.text_label,
        textContent: editForm.text_content,
      });
      if (resp.success) {
        toast.success('保存成功');
        await loadTemplates(user.id);
      } else {
        toast.error(resp.error || '保存失败');
      }
    } catch (e) {
      toast.error('保存失败');
    }
  };

  const handleDelete = async () => {
    if (!user?.id || !selectedId) return;
    try {
      const resp = await textTemplateAPI.deleteTextTemplate(user.id, selectedId);
      if (resp.success) {
        toast.success('删除成功');
        await loadTemplates(user.id);
      } else {
        toast.error(resp.error || '删除失败');
      }
    } catch (e) {
      toast.error('删除失败');
    }
  };

  const handleCreateFromEdit = async () => {
    if (!user?.id) {
      toast.error('请先登录');
      return;
    }
    const { text_name, text_label, text_content } = editForm;
    if (!text_name || !text_label || !text_content) {
      toast.error('请完整填写：模板名称、模板标签、模板内容');
      return;
    }
    try {
      const resp = await textTemplateAPI.createTextTemplate(
        user.id,
        activeType,
        text_name,
        text_label,
        text_content
      );
      if (resp && resp.success) {
        toast.success('新建成功');
        await loadTemplates(user.id);
        if (resp.text_id) {
          setSelectedId(String(resp.text_id));
        }
      } else {
        toast.error((resp && resp.error) || '新建失败');
      }
    } catch (e) {
      toast.error('新建失败');
    }
  };

  const handleCreate = async () => {
    if (!user?.id) {
      toast.error('请先登录');
      return;
    }
    if (!createForm.text_type || !createForm.text_name || !createForm.text_label || !createForm.text_content) {
      setMessage({ type: 'error', text: '请完整填写表单（类型、名称、标签、内容）' });
      return;
    }
    setIsCreating(true);
    setMessage(null);
    try {
      await textTemplateAPI.createTextTemplate(
        user.id,
        createForm.text_type,
        createForm.text_name,
        createForm.text_label,
        createForm.text_content
      );
      toast.success('创建成功');
      setCreateForm({ text_type: createForm.text_type, text_name: '', text_label: '', text_content: '' });
      await loadTemplates(user.id);
    } catch (e) {
      setMessage({ type: 'error', text: '创建失败，请重试' });
    } finally {
      setIsCreating(false);
    }
  };

  // const handleDelete = async (textId) => {
  //   if (!user?.id) {
  //     toast.error('请先登录');
  //     return;
  //   }
  //   try {
  //     const resp = await textTemplateAPI.deleteTextTemplate(user.id, textId);
  //     if (resp.success) {
  //       toast.success('删除成功');
  //       await loadTemplates(user.id);
  //     } else {
  //       toast.error(resp.error || '删除失败');
  //     }
  //   } catch (e) {
  //     toast.error('删除失败');
  //   }
  // };

  const handleCopy = async (text) => {
    try {
      await navigator.clipboard.writeText(text || '');
      toast.success('已复制到剪贴板');
    } catch (e) {
      toast.error('复制失败');
    }
  };

  const formatDate = (value) => {
    if (!value) return '';
    try {
      const d = new Date(value);
      if (isNaN(d.getTime())) return String(value);
      return d.toLocaleString();
    } catch {
      return String(value);
    }
  };

  const splitLabels = (label) => {
    if (!label) return [];
    return String(label)
      .split(/[\/,，\s]+/)
      .map(s => s.trim())
      .filter(Boolean)
      .slice(0, 5);
  };

  return (
    <div className="space-y-6">
      {message && (
        <Alert className={message.type === 'error' ? 'border-red-200 bg-red-50 text-red-700' : 'border-green-200 bg-green-50 text-green-700'}>
          <AlertDescription>{message.text}</AlertDescription>
        </Alert>
      )}

      {/* 管理区：选择/编辑已创建模板 */}
      <Card className="border-none shadow bg-white/70">
        <CardContent className="p-6 space-y-4">
          <div className="grid md:grid-cols-2 gap-4">
        <div>
              <Label className="font-medium text-slate-700">选择模板</Label>
              <Select value={selectedId} onValueChange={onSelectTemplate}>
            <SelectTrigger className="mt-2">
                  <SelectValue placeholder="选择或新建一个模板..." />
            </SelectTrigger>
            <SelectContent>
                  {currentList.map(t => (
                    <SelectItem key={t.id} value={String(t.id)}>{t.text_name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
            <div className="flex items-end">
              <div className="flex w-full gap-2">
                <Button onClick={handleCreateFromEdit} className="flex-1 bg-emerald-600 hover:bg-emerald-700">
                  <PlusCircle className="w-4 h-4" /> 新建模板
                </Button>
                <Button onClick={handleDelete} disabled={!selectedId} className="flex-1 bg-red-600 hover:bg-red-700">
                  <Trash2 className="w-4 h-4" /> 删除模板
                </Button>
                <Button onClick={handleSaveEdit} disabled={!selectedId} className="flex-1 bg-blue-600 hover:bg-blue-700 gap-1">
                  <Save className="w-4 h-4" /> 保存模板
                </Button>
              </div>
            </div>
          </div>
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <Label className="font-medium text-slate-700">模板名称</Label>
              <Input className="mt-2" value={editForm.text_name} onChange={(e) => setEditForm(prev => ({ ...prev, text_name: e.target.value }))} placeholder="为模板起一个名字" />
            </div>
            <div>
              <Label className="font-medium text-slate-700">模板标签</Label>
              <Input className="mt-2" value={editForm.text_label} onChange={(e) => setEditForm(prev => ({ ...prev, text_label: e.target.value }))} placeholder="示例：穿搭/测评/促销" />
            </div>
          </div>
          <div>
            <Label className="font-medium text-slate-700">模板内容</Label>
            <Textarea className="mt-2 h-36" value={editForm.text_content} onChange={(e) => setEditForm(prev => ({ ...prev, text_content: e.target.value }))} placeholder="编辑选择的模板内容" />
          </div>
        </CardContent>
      </Card>

      
    </div>
  );
}