'use client';

import { useState } from 'react';
import Link from 'next/link';
import BottomNav from '@/components/mobile/BottomNav';

type ComplaintType = 'شكوى' | 'مقترح' | 'استفسار';
type TabType = 'new' | 'history';

interface Complaint {
  id: number;
  title: string;
  date: string;
  status: 'pending' | 'resolved' | 'in-progress';
  statusText: string;
  type: string;
}

export default function ComplaintsPage() {
  const [activeTab, setActiveTab] = useState<TabType>('new');
  const [complaintType, setComplaintType] = useState<ComplaintType>('شكوى');
  const [title, setTitle] = useState('');
  const [details, setDetails] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);

  const complaints: Complaint[] = [
    { id: 1, title: 'مشكلة في التحقق من رقم الجوال', date: '11 مارس 2026', status: 'in-progress', statusText: 'جارية المراجعة', type: 'شكوى' },
    { id: 2, title: 'تأخر الباص عن الموعد المحدد', date: '8 مارس 2026', status: 'resolved', statusText: 'تم الحل', type: 'شكوى' },
    { id: 3, title: 'اقتراح لإضافة ميزة تتبع الباص', date: '5 مارس 2026', status: 'pending', statusText: 'قيد الانتظار', type: 'مقترح' },
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !details.trim()) return;
    setIsSubmitting(true);
    const formData = new URLSearchParams();
    formData.append('type', complaintType);
    formData.append('title', title);
    formData.append('details', details);
    try {
      const response = await fetch('https://readdy.ai/api/form/d6olborlgirdouph2t60', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString(),
      });
      if (response.ok) {
        setShowSuccess(true);
        setTitle('');
        setDetails('');
        setTimeout(() => { setShowSuccess(false); setActiveTab('history'); }, 2000);
      }
    } catch (error) {
    } finally {
      setIsSubmitting(false);
    }
  };

  const statusConfig: Record<string, { bg: string; text: string; dot: string }> = {
    pending: { bg: 'bg-sky-50', text: 'text-sky-600', dot: 'bg-sky-400' },
    'in-progress': { bg: 'bg-amber-50', text: 'text-amber-600', dot: 'bg-amber-400' },
    resolved: { bg: 'bg-emerald-50', text: 'text-emerald-600', dot: 'bg-emerald-400' },
  };

  const typeConfig: Record<ComplaintType, { icon: string; color: string; bg: string }> = {
    'شكوى': { icon: 'ri-error-warning-line', color: 'text-red-500', bg: 'bg-red-50' },
    'مقترح': { icon: 'ri-lightbulb-line', color: 'text-amber-500', bg: 'bg-amber-50' },
    'استفسار': { icon: 'ri-question-line', color: 'text-sky-500', bg: 'bg-sky-50' },
  };

  return (
    <div className="min-h-screen" dir="rtl" style={{ maxWidth: '390px', margin: '0 auto', background: '#F7F8FA' }}>
      <div className="h-11 bg-white"></div>

      <header className="h-14 bg-white border-b border-slate-100 flex items-center justify-center px-4 sticky top-0 z-10">
        <Link href="/mobile/profile" className="absolute right-4 w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer">
          <i className="ri-arrow-right-s-line text-slate-700 text-xl"></i>
        </Link>
        <h1 className="text-lg font-bold text-slate-900">الشكاوى والمقترحات</h1>
      </header>

      <div className="bg-white sticky top-14 z-10 px-4 pt-3 pb-0">
        <div className="flex bg-slate-100 rounded-2xl p-1">
          {[
            { id: 'new', label: 'شكوى جديدة', icon: 'ri-add-circle-line' },
            { id: 'history', label: 'شكاواي السابقة', icon: 'ri-history-line' },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as TabType)}
              className={`flex-1 h-10 rounded-xl text-xs font-bold transition-all cursor-pointer whitespace-nowrap flex items-center justify-center gap-1.5 ${
                activeTab === tab.id ? 'bg-white text-emerald-600 shadow-sm' : 'text-slate-500'
              }`}
            >
              <i className={`${tab.icon} text-sm`}></i>
              {tab.label}
            </button>
          ))}
        </div>
        <div className="h-3"></div>
      </div>

      <div className="p-4 pb-32">
        {activeTab === 'new' ? (
          <form id="complaints-form" data-readdy-form onSubmit={handleSubmit}>
            <div className="bg-white rounded-2xl p-4 shadow-sm border border-slate-100 space-y-4">

              <div>
                <label className="block text-xs font-bold text-slate-500 mb-2">نوع الطلب</label>
                <div className="grid grid-cols-3 gap-2">
                  {(['شكوى', 'مقترح', 'استفسار'] as ComplaintType[]).map((type) => (
                    <button
                      key={type}
                      type="button"
                      onClick={() => setComplaintType(type)}
                      className={`h-16 rounded-xl flex flex-col items-center justify-center gap-1.5 cursor-pointer transition-all active:scale-95 border-2 ${
                        complaintType === type
                          ? 'border-emerald-500 bg-emerald-50'
                          : 'border-slate-200 bg-slate-50'
                      }`}
                    >
                      <div className={`w-8 h-8 ${typeConfig[type].bg} rounded-lg flex items-center justify-center`}>
                        <i className={`${typeConfig[type].icon} ${typeConfig[type].color} text-lg`}></i>
                      </div>
                      <span className={`text-xs font-bold ${complaintType === type ? 'text-emerald-700' : 'text-slate-500'}`}>{type}</span>
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-500 mb-1.5">
                  عنوان {complaintType === 'شكوى' ? 'الشكوى' : complaintType === 'مقترح' ? 'المقترح' : 'الاستفسار'}
                </label>
                <input
                  type="text"
                  name="title"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  placeholder="أدخلي العنوان"
                  className="w-full h-[52px] px-4 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-emerald-400 focus:border-transparent"
                  required
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-500 mb-1.5">التفاصيل</label>
                <textarea
                  name="details"
                  value={details}
                  onChange={(e) => { if (e.target.value.length <= 500) setDetails(e.target.value); }}
                  placeholder="اكتبي التفاصيل هنا..."
                  className="w-full h-[140px] px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-emerald-400 focus:border-transparent resize-none"
                  required
                  maxLength={500}
                ></textarea>
                <div className="flex justify-between mt-1">
                  <span className="text-[10px] text-slate-400">{details.length}/500</span>
                </div>
              </div>

              <button
                type="submit"
                disabled={isSubmitting || !title.trim() || !details.trim()}
                className="w-full h-[52px] text-white rounded-xl font-bold text-sm flex items-center justify-center gap-2 cursor-pointer transition-all disabled:opacity-40 disabled:cursor-not-allowed active:scale-95 whitespace-nowrap shadow-md"
                style={{ background: 'linear-gradient(135deg, #059669, #047857)' }}
              >
                {isSubmitting ? (
                  <><i className="ri-loader-4-line text-xl animate-spin"></i> جاري الإرسال...</>
                ) : (
                  <><i className="ri-send-plane-fill text-lg"></i> إرسال الطلب</>
                )}
              </button>
            </div>
          </form>
        ) : (
          <div className="space-y-3">
            {complaints.map((complaint) => {
              const cfg = statusConfig[complaint.status];
              return (
                <div key={complaint.id} className="bg-white rounded-2xl p-4 shadow-sm border border-slate-100">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-start gap-2 flex-1">
                      <div className={`w-8 h-8 ${typeConfig[complaint.type as ComplaintType]?.bg || 'bg-slate-50'} rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5`}>
                        <i className={`${typeConfig[complaint.type as ComplaintType]?.icon || 'ri-file-line'} ${typeConfig[complaint.type as ComplaintType]?.color || 'text-slate-500'} text-sm`}></i>
                      </div>
                      <h3 className="text-sm font-bold text-slate-900 flex-1 leading-snug">{complaint.title}</h3>
                    </div>
                    <span className={`px-2.5 py-1 ${cfg.bg} ${cfg.text} rounded-full text-[10px] font-bold whitespace-nowrap mr-2 flex items-center gap-1`}>
                      <span className={`w-1.5 h-1.5 ${cfg.dot} rounded-full`}></span>
                      {complaint.statusText}
                    </span>
                  </div>
                  <div className="flex items-center justify-between pt-2.5 border-t border-slate-100">
                    <div className="flex items-center gap-1.5">
                      <div className="w-4 h-4 flex items-center justify-center">
                        <i className="ri-calendar-line text-slate-400 text-xs"></i>
                      </div>
                      <span className="text-xs text-slate-400">{complaint.date}</span>
                    </div>
                    <button className="text-xs text-emerald-600 font-bold cursor-pointer hover:text-emerald-700 whitespace-nowrap flex items-center gap-1">
                      <i className="ri-eye-line text-xs"></i>
                      تفاصيل
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {showSuccess && (
        <div className="fixed top-20 left-1/2 -translate-x-1/2 text-white px-5 py-3 rounded-2xl shadow-2xl z-50 flex items-center gap-2" style={{ background: 'linear-gradient(135deg, #059669, #047857)' }}>
          <i className="ri-checkbox-circle-fill text-xl"></i>
          <span className="font-bold text-sm whitespace-nowrap">تم إرسال طلبك بنجاح!</span>
        </div>
      )}

      <BottomNav activeTab="more" />
    </div>
  );
}
