import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Zap, Send, Mic, Calendar, Clock, ArrowLeft, Users, MapPin, Edit2, CheckCircle } from "lucide-react";
import { format } from "date-fns";

export default function RapidOrderInterface({ onBack, onSubmit }) {
  const [message, setMessage] = useState("");
  const [isProcessing, setIsProcessing] = useState(false);
  const [parsedData, setParsedData] = useState(null);
  const [showConfirmation, setShowConfirmation] = useState(false);
  
  const handleBack = () => {
    if (onBack) onBack();
  };

  const examples = [
    { text: "We had a call out. Need 2 cooks ASAP", color: "bg-blue-50 border-blue-200 text-blue-700" },
    { text: "Need 5 bartenders ASAP until 5am", color: "bg-purple-50 border-purple-200 text-purple-700" },
    { text: "Emergency! Need 3 servers right now till midnight", color: "bg-green-50 border-green-200 text-green-700" },
  ];

  const parseRapidMessage = (msg) => {
    // Extract count (numbers)
    const countMatch = msg.match(/(\d+)/);
    const count = countMatch ? parseInt(countMatch[1]) : 1;
    
    // Extract role (common keywords)
    const roles = ['server', 'cook', 'chef', 'bartender', 'dishwasher', 'host', 'runner'];
    let role = 'staff';
    for (const r of roles) {
      if (msg.toLowerCase().includes(r)) {
        role = r + (count > 1 ? 's' : '');
        break;
      }
    }
    
    // Extract time (until X, till X, by X)
    const timeMatch = msg.match(/until\s+(\d+(?::\d+)?\s*(?:am|pm)?)|till\s+(\d+(?::\d+)?\s*(?:am|pm)?)|by\s+(\d+(?::\d+)?\s*(?:am|pm)?)/i);
    const endTime = timeMatch ? (timeMatch[1] || timeMatch[2] || timeMatch[3]) : '11:59pm';
    
    // Current time as start
    const now = new Date();
    const startTime = format(now, 'h:mm a');
    
    return {
      count,
      role,
      startTime,
      endTime,
      location: "Client's location" // Default, can be auto-detected
    };
  };

  const handleSend = async () => {
    if (!message.trim()) return;
    setIsProcessing(true);
    
    // Parse the message
    const parsed = parseRapidMessage(message);
    setParsedData(parsed);
    setShowConfirmation(true);
    
    setIsProcessing(false);
  };

  const handleConfirm = () => {
    if (onSubmit && parsedData) {
      onSubmit({ 
        rawMessage: message, 
        orderType: 'rapid',
        ...parsedData
      });
    }
  };

  const handleEdit = () => {
    setShowConfirmation(false);
    setParsedData(null);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleExampleClick = (exampleText) => {
    setMessage(exampleText);
  };

  return (
    <div className="bg-white rounded-2xl shadow-lg border-2 border-red-200 overflow-hidden">
      <div className="bg-gradient-to-r from-red-500 to-orange-500 p-4 text-white">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
              <Zap className="w-6 h-6" />
            </div>
            <div>
              <h2 className="text-xl font-bold flex items-center gap-2">
                <Zap className="w-5 h-5" />
                RAPID Order
              </h2>
              <p className="text-red-100 text-xs">Emergency staffing in minutes</p>
            </div>
          </div>
          <div className="text-right text-xs text-red-100">
            <div className="flex items-center gap-2">
              <Calendar className="w-3 h-3" />
              {format(new Date(), 'EEE, MMM dd, yyyy')}
            </div>
            <div className="flex items-center gap-2 mt-0.5">
              <Clock className="w-3 h-3" />
              {format(new Date(), 'h:mm a')}
            </div>
          </div>
        </div>
      </div>

      <div className="p-6">
        {/* Section Header */}
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-semibold text-slate-900">Tell us what you need</h3>
          <Badge className="bg-red-500 text-white text-xs">URGENT</Badge>
        </div>

        {/* Main Content */}
        <div className="space-y-4">
          {/* Icon + Message */}
          <div className="text-center py-4">
            <div className="w-16 h-16 bg-gradient-to-br from-red-500 to-orange-500 rounded-xl flex items-center justify-center mx-auto mb-3 shadow-lg">
              <Zap className="w-8 h-8 text-white" />
            </div>
            <h4 className="text-lg font-bold text-slate-900 mb-1">Need staff urgently?</h4>
            <p className="text-sm text-slate-600">Type or speak what you need. I'll handle the rest</p>
          </div>

          {/* Example Prompts */}
          <div className="space-y-2">
            {examples.map((example, idx) => (
              <button
                key={idx}
                onClick={() => handleExampleClick(example.text)}
                className={`w-full p-3 rounded-lg border-2 text-left transition-all hover:shadow-md text-sm ${example.color}`}
              >
                <span className="font-semibold">Example:</span> "{example.text}"
              </button>
            ))}
          </div>

          {/* Input Area */}
          {showConfirmation && parsedData ? (
            <div className="space-y-4">
              {/* AI Confirmation Card */}
              <div className="bg-gradient-to-br from-orange-50 to-red-50 border-2 border-orange-200 rounded-xl p-4">
                <div className="flex items-start gap-3 mb-3">
                  <div className="w-8 h-8 bg-gradient-to-br from-red-500 to-orange-500 rounded-full flex items-center justify-center flex-shrink-0">
                    <Zap className="w-4 h-4 text-white" />
                  </div>
                  <div className="flex-1">
                    <p className="text-xs font-bold text-red-600 uppercase mb-1">AI Assistant</p>
                    <p className="text-sm text-slate-700">
                      Is this a RAPID ORDER for <strong>**{parsedData.count} {parsedData.role}**</strong> at <strong>**{parsedData.location}**</strong>?
                    </p>
                  </div>
                </div>

                <div className="space-y-2 mb-4">
                  <p className="text-xs text-slate-600">Start Time: <strong className="text-slate-900">{parsedData.startTime}</strong></p>
                  <p className="text-xs text-slate-600">End Time: <strong className="text-slate-900">{parsedData.endTime}</strong></p>
                </div>

                {/* Details Card */}
                <div className="bg-white border-2 border-blue-200 rounded-lg p-3 space-y-2">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
                      <Users className="w-4 h-4 text-white" />
                    </div>
                    <div>
                      <p className="text-[10px] text-blue-600 font-semibold uppercase">Staff Needed</p>
                      <p className="text-sm font-bold text-slate-900">{parsedData.count} {parsedData.role}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
                      <MapPin className="w-4 h-4 text-white" />
                    </div>
                    <div>
                      <p className="text-[10px] text-blue-600 font-semibold uppercase">Location</p>
                      <p className="text-sm font-bold text-slate-900">{parsedData.location}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
                      <Clock className="w-4 h-4 text-white" />
                    </div>
                    <div>
                      <p className="text-[10px] text-blue-600 font-semibold uppercase">Time</p>
                      <p className="text-sm font-bold text-slate-900">Start: {parsedData.startTime} | End: {parsedData.endTime}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex gap-3">
                <Button
                  onClick={handleConfirm}
                  className="flex-1 h-11 bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white font-bold shadow-lg"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  CONFIRM & SEND
                </Button>
                <Button
                  onClick={handleEdit}
                  variant="outline"
                  className="h-11 px-6 border-2 border-slate-300 hover:border-slate-400"
                >
                  <Edit2 className="w-4 h-4 mr-2" />
                  EDIT
                </Button>
              </div>
            </div>
          ) : (
            <div className="space-y-2">
              <Textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder='Type or speak... (e.g., "Need 5 cooks ASAP until 5am")'
                rows={3}
                className="resize-none border-2 border-slate-200 focus:border-red-400 rounded-lg text-sm"
              />

              {/* Action Buttons */}
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  className="flex-1 h-10 border-2 border-slate-300 hover:border-slate-400 text-sm"
                >
                  <Mic className="w-4 h-4 mr-2" />
                  Speak
                </Button>
                <Button
                  onClick={handleSend}
                  disabled={!message.trim() || isProcessing}
                  className="flex-1 h-10 bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white font-semibold shadow-lg text-sm"
                >
                  <Send className="w-4 h-4 mr-2" />
                  {isProcessing ? 'Processing...' : 'Send Message'}
                </Button>
              </div>
            </div>
          )}

          {/* Tip */}
          <div className="bg-blue-50 border-2 border-blue-200 rounded-lg p-3">
            <div className="flex gap-2">
              <div className="w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-white text-xs font-bold">i</span>
              </div>
              <div className="text-xs text-blue-900">
                <span className="font-semibold">Tip:</span> Include role, quantity, and urgency for fastest processing. Optionally add end time like "until 5am" or "till midnight". AI will auto-detect your location and send to your preferred vendor with priority notification.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}