
import React, { useState } from 'react';
import { useToast } from '../../context/ToastContext';
import { useData } from '../../context/DataContext';

export const DoctorSettings: React.FC = () => {
  const { addToast } = useToast();
  const { clinicType } = useData();
  const [activeTab, setActiveTab] = useState<'info' | 'branding' | 'api'>('info');
  
  const [clinicName, setClinicName] = useState("عيادة الشفاء");
  const [specialty, setSpecialty] = useState(
    clinicType === 'dental' ? "طب وجراحة الأسنان" : 
    clinicType === 'obgyn' ? "نسائية وتوليد" : "طب عام"
  );
  const [address, setAddress] = useState("شارع فلسطين، بجوار الصيدلية المركزية");
  const [phone, setPhone] = useState("0912345678");

  // Specialty specific states
  const [licenseNo, setLicenseNo] = useState("");
  const [hospitalAffiliation, setHospitalAffiliation] = useState("");
  const [labPartner, setLabPartner] = useState("");

  // API State
  const [apiKey, setApiKey] = useState("cl_live_78234872348...");
  const [isSaving, setIsSaving] = useState(false);

  const handleSave = () => {
    setIsSaving(true);
    // Simulate API call
    setTimeout(() => {
        setIsSaving(false);
        addToast('تم حفظ إعدادات العيادة وتحديث البيانات بنجاح', 'success');
    }, 1000);
  };

  const regenerateKey = () => {
      if(window.confirm('هل أنت متأكد؟ سيتوقف أي نظام يستخدم المفتاح الحالي.')) {
        setApiKey(`cl_live_${Math.random().toString(36).substring(2, 15)}...`);
        addToast('تم توليد مفتاح API جديد', 'success');
      }
  };

  const themeColor = clinicType === 'dental' ? 'bg-emerald-600 hover:bg-emerald-700' : clinicType === 'obgyn' ? 'bg-rose-500 hover:bg-rose-600' : 'bg-primary hover:bg-primary-dark';

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <header className="mb-6 flex justify-between items-end">
        <div>
            <h2 className="text-2xl font-bold text-gray-800">إعدادات العيادة</h2>
            <p className="text-gray-500">تخصيص معلومات العيادة والمظهر</p>
        </div>
        <span className={`px-3 py-1 rounded-full text-xs font-bold text-white uppercase ${clinicType === 'dental' ? 'bg-emerald-500' : clinicType === 'obgyn' ? 'bg-rose-500' : 'bg-blue-500'}`}>
            {clinicType} Settings
        </span>
      </header>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 mb-6 overflow-x-auto">
          <button 
            onClick={() => setActiveTab('info')}
            className={`px-6 py-3 font-medium text-sm transition-colors border-b-2 whitespace-nowrap ${activeTab === 'info' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
          >
              المعلومات الأساسية
          </button>
          <button 
            onClick={() => setActiveTab('branding')}
            className={`px-6 py-3 font-medium text-sm transition-colors border-b-2 whitespace-nowrap ${activeTab === 'branding' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
          >
              الشعار والمظهر
          </button>
          <button 
            onClick={() => setActiveTab('api')}
            className={`px-6 py-3 font-medium text-sm transition-colors border-b-2 whitespace-nowrap ${activeTab === 'api' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
          >
              الربط البرمجي (API)
          </button>
      </div>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 md:p-8">
        
        {activeTab === 'info' && (
            <form className="space-y-8 animate-fade-in">
            {/* Clinic Info */}
            <section>
                <h3 className="text-lg font-bold text-gray-800 mb-4 pb-2 border-b border-gray-100">المعلومات الأساسية</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">اسم العيادة</label>
                    <input 
                    type="text" 
                    value={clinicName} 
                    onChange={(e) => setClinicName(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" 
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">التخصص</label>
                    <input 
                    type="text" 
                    value={specialty}
                    onChange={(e) => setSpecialty(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" 
                    />
                </div>
                
                {/* Conditional Fields based on Clinic Type */}
                {clinicType === 'dental' && (
                    <>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">رقم الترخيص الطبي</label>
                            <input type="text" value={licenseNo} onChange={e => setLicenseNo(e.target.value)} className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" placeholder="Dental License #" />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">معمل الأسنان المتعاون</label>
                            <input type="text" value={labPartner} onChange={e => setLabPartner(e.target.value)} className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" placeholder="اسم المعمل" />
                        </div>
                    </>
                )}

                {clinicType === 'obgyn' && (
                    <>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">المستشفى التابع (للولادة)</label>
                            <input type="text" value={hospitalAffiliation} onChange={e => setHospitalAffiliation(e.target.value)} className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" placeholder="اسم المستشفى" />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">رقم الطوارئ</label>
                            <input type="text" className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" placeholder="للخالات الطارئة" />
                        </div>
                    </>
                )}

                <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 mb-1">العنوان</label>
                    <input 
                    type="text" 
                    value={address}
                    onChange={(e) => setAddress(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" 
                    />
                </div>
                <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 mb-1">وصف العيادة</label>
                    <textarea rows={3} className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900"></textarea>
                </div>
                </div>
            </section>

            {/* Contact Info */}
            <section>
                <h3 className="text-lg font-bold text-gray-800 mb-4 pb-2 border-b border-gray-100">التواصل</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">رقم الهاتف</label>
                    <input 
                    type="tel" 
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" 
                    dir="ltr" 
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">البريد الإلكتروني</label>
                    <input type="email" defaultValue="clinic@example.com" className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" dir="ltr" />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">رقم الواتساب</label>
                    <input type="tel" className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900" dir="ltr" placeholder="+966..." />
                </div>
                </div>
            </section>

            {/* Working Hours */}
            <section>
                <h3 className="text-lg font-bold text-gray-800 mb-4 pb-2 border-b border-gray-100">أوقات الدوام</h3>
                <div className="space-y-3">
                {['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس'].map(day => (
                    <div key={day} className="flex items-center gap-4">
                    <div className="w-24 font-medium text-gray-700">{day}</div>
                    <input type="time" defaultValue="09:00" className="px-3 py-1.5 border border-gray-300 rounded-md text-sm bg-white text-gray-900" />
                    <span className="text-gray-500">إلى</span>
                    <input type="time" defaultValue="17:00" className="px-3 py-1.5 border border-gray-300 rounded-md text-sm bg-white text-gray-900" />
                    </div>
                ))}
                </div>
            </section>

            <div className="pt-4 flex justify-end">
                <button 
                type="button" 
                onClick={handleSave}
                disabled={isSaving}
                className={`text-white px-8 py-3 rounded-xl shadow-md transition-all font-bold flex items-center gap-2 ${themeColor}`}
                >
                {isSaving ? 'جاري الحفظ...' : 'حفظ التغييرات'}
                {isSaving && <i className="fas fa-spinner fa-spin"></i>}
                </button>
            </div>
            </form>
        )}

        {activeTab === 'branding' && (
            <div className="space-y-8 animate-fade-in">
                <section>
                    <h3 className="text-lg font-bold text-gray-800 mb-4 pb-2 border-b border-gray-100">شعار العيادة</h3>
                    <div className="flex flex-col items-center p-8 border-2 border-dashed border-gray-300 rounded-2xl bg-gray-50 hover:bg-gray-100 transition-colors cursor-pointer group">
                        <div className="w-24 h-24 bg-white rounded-full shadow-md flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
                            <i className="fas fa-image text-3xl text-gray-400"></i>
                        </div>
                        <p className="text-gray-600 font-medium">اضغط لرفع شعار العيادة (Logo)</p>
                        <p className="text-xs text-gray-400 mt-1">PNG, JPG بحد أقصى 2MB</p>
                    </div>
                </section>

                <section>
                    <h3 className="text-lg font-bold text-gray-800 mb-4 pb-2 border-b border-gray-100">ألوان الهوية</h3>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="space-y-2">
                            <label className="text-sm font-bold text-gray-700">اللون الأساسي</label>
                            <input type="color" className="w-full h-10 rounded-lg cursor-pointer border border-gray-200" defaultValue="#007bff" />
                        </div>
                        <div className="space-y-2">
                            <label className="text-sm font-bold text-gray-700">اللون الثانوي</label>
                            <input type="color" className="w-full h-10 rounded-lg cursor-pointer border border-gray-200" defaultValue="#6c757d" />
                        </div>
                    </div>
                </section>

                <div className="pt-4 flex justify-end">
                    <button 
                        type="button" 
                        onClick={handleSave}
                        className={`text-white px-8 py-3 rounded-xl shadow-md transition-all font-bold flex items-center gap-2 ${themeColor}`}
                    >
                        حفظ المظهر
                    </button>
                </div>
            </div>
        )}

        {activeTab === 'api' && (
            <div className="space-y-6 animate-fade-in">
                <div className="bg-blue-50 border border-blue-100 rounded-xl p-6">
                    <h3 className="font-bold text-blue-800 mb-2">ربط العيادة مع أنظمة خارجية</h3>
                    <p className="text-sm text-blue-600 mb-4">
                        يمكنك استخدام مفتاح API لربط موقع عيادتك بتطبيقات الطرف الثالث، مثل أنظمة المحاسبة، أو منصات الحجوزات الموحدة.
                    </p>
                    <div className="bg-white border border-blue-200 rounded-lg p-3 flex justify-between items-center">
                        <code className="text-gray-600 font-mono text-sm">{apiKey}</code>
                        <button className="text-blue-600 hover:text-blue-800 text-sm font-bold" onClick={() => navigator.clipboard.writeText(apiKey)}>
                            نسخ
                        </button>
                    </div>
                    <button onClick={regenerateKey} className="mt-4 text-xs text-red-500 hover:underline">
                        إعادة توليد المفتاح (خطير)
                    </button>
                </div>

                <div>
                    <h4 className="font-bold text-gray-800 mb-4">الصلاحيات المتاحة عبر API</h4>
                    <ul className="space-y-2 text-sm text-gray-600">
                        <li className="flex items-center gap-2">
                            <i className="fas fa-check text-green-500"></i> قراءة المواعيد
                        </li>
                        <li className="flex items-center gap-2">
                            <i className="fas fa-check text-green-500"></i> إنشاء حجوزات جديدة
                        </li>
                        <li className="flex items-center gap-2">
                            <i className="fas fa-times text-red-500"></i> الوصول لبيانات المرضى الحساسة (يتطلب صلاحية خاصة)
                        </li>
                    </ul>
                </div>

                <div className="pt-4 border-t border-gray-100">
                    <a href="#" className="text-primary hover:underline text-sm font-medium flex items-center gap-1">
                        <i className="fas fa-book"></i>
                        قراءة وثائق المطورين (Documentation)
                    </a>
                </div>
            </div>
        )}

      </div>
    </div>
  );
};
