/**
 * Call Scripts Manager UI Component
 */

import React, { useState, useEffect } from 'react';

interface CallScript {
  id: string;
  name: string;
  category: string;
  tone: string;
  escalationLevel: number;
  greeting: string;
  mainContent: string;
  closingPositive: string;
  isDefault: boolean;
}

export function CallScriptsManager() {
  const [scripts, setScripts] = useState<CallScript[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [selectedScript, setSelectedScript] = useState<CallScript | null>(null);

  useEffect(() => {
    fetchScripts();
  }, []);

  const fetchScripts = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/plugins/database-connector/scripts');
      const data = await response.json();
      setScripts(data.scripts || []);
    } catch (error) {
      console.error('Failed to fetch scripts:', error);
    } finally {
      setLoading(false);
    }
  };

  const getCategoryLabel = (category: string) => {
    const labels: Record<string, string> = {
      'payment_reminder_friendly': 'تذكير ودي',
      'payment_reminder_firm': 'تذكير حازم',
      'payment_reminder_urgent': 'تذكير عاجل',
      'follow_up': 'متابعة',
      'appointment_confirmation': 'تأكيد موعد',
    };
    return labels[category] || category;
  };

  const getToneLabel = (tone: string) => {
    const labels: Record<string, string> = {
      'friendly': 'ودي',
      'professional': 'مهني',
      'firm': 'حازم',
      'urgent': 'عاجل',
    };
    return labels[tone] || tone;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="p-6" dir="rtl">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">📝 نصوص المكالمات</h1>
          <p className="text-muted-foreground">إدارة قوالب نصوص المكالمات</p>
        </div>
        <button
          onClick={() => setShowForm(true)}
          className="bg-primary text-primary-foreground px-4 py-2 rounded-lg"
        >
          + نص جديد
        </button>
      </div>

      {/* Scripts Grid */}
      <div className="grid grid-cols-2 gap-4">
        {scripts.map((script) => (
          <div 
            key={script.id} 
            className="bg-card border rounded-lg p-4 cursor-pointer hover:border-primary"
            onClick={() => setSelectedScript(script)}
          >
            <div className="flex justify-between items-start mb-2">
              <h3 className="font-semibold">{script.name}</h3>
              <div className="flex gap-1">
                <span className="text-xs bg-muted px-2 py-1 rounded">
                  {getCategoryLabel(script.category)}
                </span>
                <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
                  {getToneLabel(script.tone)}
                </span>
              </div>
            </div>
            
            <p className="text-sm text-muted-foreground line-clamp-2 mb-2">
              {script.greeting}
            </p>
            
            <div className="flex items-center justify-between text-xs">
              <span>مستوى التصعيد: {script.escalationLevel}/5</span>
              {script.isDefault && (
                <span className="bg-green-100 text-green-800 px-2 py-0.5 rounded">افتراضي</span>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Script Preview Modal */}
      {selectedScript && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-background rounded-lg w-full max-w-2xl max-h-[80vh] overflow-y-auto p-6">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold">{selectedScript.name}</h2>
              <button onClick={() => setSelectedScript(null)} className="text-2xl">&times;</button>
            </div>

            <div className="space-y-4">
              <div>
                <h4 className="font-medium text-sm text-muted-foreground mb-1">الترحيب</h4>
                <p className="bg-muted p-3 rounded">{selectedScript.greeting}</p>
              </div>

              <div>
                <h4 className="font-medium text-sm text-muted-foreground mb-1">المحتوى الرئيسي</h4>
                <p className="bg-muted p-3 rounded whitespace-pre-wrap">{selectedScript.mainContent}</p>
              </div>

              <div>
                <h4 className="font-medium text-sm text-muted-foreground mb-1">الختام الإيجابي</h4>
                <p className="bg-green-50 p-3 rounded border border-green-200">{selectedScript.closingPositive}</p>
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-6 pt-4 border-t">
              <button onClick={() => setSelectedScript(null)} className="px-4 py-2 border rounded-lg">
                إغلاق
              </button>
              <button className="bg-primary text-primary-foreground px-4 py-2 rounded-lg">
                تعديل
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default CallScriptsManager;
