import React, { useState } from 'react';
import { FaTimes } from 'react-icons/fa';
import VoiceStatusWidget from './VoiceStatusWidget';

interface VoiceStatusModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedRows: Set<string>;
  onUpdateSuccess: () => void;
  doctype?: string;
  fieldname?: string;
  statusOptions?: StatusOption[];
  widgetTitle?: string;
  showLanguageToggle?: boolean;
  noSelectionLabel?: string;
}

export interface StatusOption {
  value: string;
  label: string;
  /** Arabic display label shown in pills and hints */
  arLabel?: string;
  keywords: string[];
  color: 'completed' | 'in-progress' | 'not-started';
  icon: string;
}

// ─── Work Order statuses (English only) ──────────────────────────────────────
const WO_STATUS_OPTIONS: StatusOption[] = [
  {
    value: 'Open',
    label: 'Open',
    keywords: ['open'],
    color: 'not-started',
    icon: '⏳',
  },
  {
    value: 'Work In Progress',
    label: 'Work In Progress',
    keywords: ['work in progress'],
    color: 'in-progress',
    icon: '🔄',
  },
  {
    value: 'Closed',
    label: 'Closed',
    keywords: ['closed'],
    color: 'completed',
    icon: '✅',
  },
];

// ─── Project statuses (English + Arabic) ─────────────────────────────────────
export const PROJECT_STATUS_OPTIONS: StatusOption[] = [
  {
    value: 'Open',
    label: 'Open',
    arLabel: 'مفتوح',
    keywords: [
      // English
      'open',
      // Arabic — multiple common pronunciations / spellings
      'مفتوح', 'مفتوحة', 'افتح', 'open',
    ],
    color: 'not-started',
    icon: '📂',
  },
  {
    value: 'Completed',
    label: 'Completed',
    arLabel: 'مكتمل',
    keywords: [
      // English
      'completed', 'complete', 'done', 'finish', 'finished',
      // Arabic
      'مكتمل', 'مكتملة', 'اكتمل', 'منجز', 'منتهي', 'منتهية', 'تم',
    ],
    color: 'completed',
    icon: '✅',
  },
  {
    value: 'Cancelled',
    label: 'Cancelled',
    arLabel: 'ملغي',
    keywords: [
      // English
      'cancelled', 'canceled', 'cancel',
      // Arabic
      'ملغي', 'ملغاة', 'ملغى', 'الغي', 'إلغاء',
    ],
    color: 'in-progress',
    icon: '🚫',
  },
];

// ─── Component ────────────────────────────────────────────────────────────────
const VoiceStatusModal: React.FC<VoiceStatusModalProps> = ({
  isOpen,
  onClose,
  selectedRows,
  onUpdateSuccess,
  doctype = 'Work_Order',
  fieldname = 'repair_status',
  statusOptions = WO_STATUS_OPTIONS,
  widgetTitle = 'Voice Status Update',
  showLanguageToggle = false,
  noSelectionLabel = 'row',
}) => {
  const [isUpdating, setIsUpdating] = useState(false);

  if (!isOpen) return null;

  const selectedCount = selectedRows.size;

  const handleStatusConfirmed = async (status: string) => {
    if (selectedCount === 0) return;

    const rowsToUpdate = Array.from(selectedRows);
    setIsUpdating(true);

    let successCount = 0;
    let failCount = 0;

    for (const docName of rowsToUpdate) {
      try {
        const res = await fetch('/api/method/frappe.client.set_value', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Frappe-CSRF-Token': (window as any).csrf_token || 'fetch',
          },
          credentials: 'include',
          body: JSON.stringify({ doctype, name: docName, fieldname, value: status }),
        });
        const data = await res.json();
        if (data.exc || data.exception) throw new Error(data.exc || data.exception);
        successCount++;
      } catch (err) {
        console.error(`Failed to update ${docName}:`, err);
        failCount++;
      }
    }

    setIsUpdating(false);

    if (successCount > 0 && failCount === 0) {
      setTimeout(() => { onUpdateSuccess(); onClose(); }, 2000);
    } else if (successCount > 0) {
      onUpdateSuccess();
    }
  };

  return (
    <div
      className="fixed inset-0 bg-black/60 flex items-center justify-center z-[80] p-4"
      onClick={(e) => { if (e.target === e.currentTarget && !isUpdating) onClose(); }}
    >
      <div className="relative animate-scale-in">
        <button
          onClick={() => { if (!isUpdating) onClose(); }}
          className="absolute -top-3 -right-3 z-10 w-8 h-8 rounded-full bg-gray-600 hover:bg-gray-500 text-white flex items-center justify-center shadow-lg transition-colors"
          disabled={isUpdating}
          title="Close"
        >
          <FaTimes size={12} />
        </button>

        <VoiceStatusWidget
          onStatusConfirmed={handleStatusConfirmed}
          selectedCount={selectedCount}
          selectedNames={Array.from(selectedRows)}
          isUpdating={isUpdating}
          statusOptions={statusOptions}
          widgetTitle={widgetTitle}
          showLanguageToggle={showLanguageToggle}
          noSelectionLabel={noSelectionLabel}
        />
      </div>

      <style>{`
        @keyframes scale-in {
          from { transform: scale(0.92); opacity: 0; }
          to   { transform: scale(1);    opacity: 1; }
        }
        .animate-scale-in { animation: scale-in 0.2s ease-out; }
      `}</style>
    </div>
  );
};

export default VoiceStatusModal;