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

interface VoiceTaskUpdateModalProps {
  isOpen: boolean;
  onClose: () => void;
  taskName: string;
  onUpdateSuccess: () => void;
}

function todayFrappe(): string {
  const d = new Date();
  const yyyy = d.getFullYear();
  const mm   = String(d.getMonth() + 1).padStart(2, '0');
  const dd   = String(d.getDate()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd}`;
}

const VoiceTaskUpdateModal: React.FC<VoiceTaskUpdateModalProps> = ({
  isOpen,
  onClose,
  taskName,
  onUpdateSuccess,
}) => {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');

  if (!isOpen) return null;

  const handleUpdateConfirmed = async (text: string) => {
    if (!taskName || !text.trim()) return;

    setIsSubmitting(true);
    setErrorMsg('');

    try {
      // ── Step 1: fetch current document ──────────────────────────────
      const getRes = await fetch(
        `/api/resource/Task/${encodeURIComponent(taskName)}`,
        { credentials: 'include' }
      );
      const getData = await getRes.json();

      if (getData.exc || getData.exception) {
        throw new Error(getData.exc || getData.exception || 'Failed to fetch task');
      }

      const doc = getData.data;

      const existingRows: any[] = (doc.custom_task_updates || []).map((r: any) => ({
        name:    r.name,
        update_: r.update_,
        date:    r.date,
        task:    r.task,
      }));

      // ── Step 2: append new row ───────────────────────────────────────
      const newRow = {
        doctype: 'Updates',
        update_: text.trim(),
        date:    todayFrappe(),
        task:    taskName,
      };

      const updatedRows = [...existingRows, newRow];

      // ── Step 3: PUT back ─────────────────────────────────────────────
      const putRes = await fetch(
        `/api/resource/Task/${encodeURIComponent(taskName)}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'X-Frappe-CSRF-Token': (window as any).csrf_token || 'fetch',
          },
          credentials: 'include',
          body: JSON.stringify({
            custom_task_updates: updatedRows,
          }),
        }
      );

      const putData = await putRes.json();

      if (putData.exc || putData.exception) {
        throw new Error(putData.exc || putData.exception || 'Failed to save update');
      }

      // ── Success: close immediately then refetch ───────────────────────
      // Close first so the widget never gets a chance to replay the prompt
      onClose();
      onUpdateSuccess();

    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Unknown error';
      setErrorMsg(`Failed to save: ${msg}`);
    } finally {
      setIsSubmitting(false);
    }
  };

  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 && !isSubmitting) onClose();
      }}
    >
      <div className="relative animate-scale-in">
        <button
          onClick={() => { if (!isSubmitting) 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={isSubmitting}
          title="Close"
        >
          <FaTimes size={12} />
        </button>

        {errorMsg && (
          <div className="mb-3 px-4 py-2 bg-red-50 border border-red-300 rounded-lg text-red-700 text-sm font-medium flex items-center gap-2">
            ⚠️ {errorMsg}
            <button onClick={() => setErrorMsg('')} className="ml-auto text-red-400 hover:text-red-600">
              <FaTimes size={10} />
            </button>
          </div>
        )}

        <VoiceTaskUpdateWidget
          onUpdateConfirmed={handleUpdateConfirmed}
          isSubmitting={isSubmitting}
        />
      </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 VoiceTaskUpdateModal;