import React, { useEffect, useState } from 'react';
import { supabase } from './supabaseClient';
import { Button } from '../components/ui/Button';
import { Input } from '../components/ui/Input';
import { CalendarClock, Clock, CheckCircle2, XCircle, AlertCircle, Edit2, Trash2, X, Save } from 'lucide-react';
import toast from 'react-hot-toast';

export const Scheduler = () => {
  const [campaigns, setCampaigns] = useState<any[]>([]);
  const [templates, setTemplates] = useState<any[]>([]);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<any>({});
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchTemplates();
    fetchCampaigns();
  }, []);

  const fetchTemplates = async () => {
    const { data } = await supabase.from('templates').select('*');
    if (data) setTemplates(data);
  };

  const fetchCampaigns = async () => {
    setIsLoading(true);
    const { data, error } = await supabase
      .from('scheduled_campaigns')
      .select('*, templates(title)')
      .order('created_at', { ascending: false });
    
    if (error) {
      toast.error('Failed to load campaigns: ' + error.message);
    } else if (data) {
      setCampaigns(data);
    }
    setIsLoading(false);
  };

  const handleEditClick = (campaign: any) => {
    setEditingId(campaign.id);
    // Format datetime for datetime-local input
    const localDate = new Date(campaign.scheduled_at);
    // Adjust to local timezone format YYYY-MM-DDTHH:mm
    const tzOffset = localDate.getTimezoneOffset() * 60000;
    const localISOTime = (new Date(localDate.getTime() - tzOffset)).toISOString().slice(0, 16);

    setEditForm({
      ...campaign,
      scheduled_at: localISOTime
    });
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setEditForm({});
  };

  const handleSaveEdit = async () => {
    if (!editForm.scheduled_at) {
      toast.error("Scheduled time is required.");
      return;
    }

    const scheduledTime = new Date(editForm.scheduled_at);
    if (scheduledTime <= new Date()) {
      toast.error("Scheduled time must be in the future.");
      return;
    }

    const { error } = await supabase
      .from('scheduled_campaigns')
      .update({
        template_id: editForm.template_id,
        target_table: editForm.target_table,
        start_row: parseInt(editForm.start_row),
        batch_count: parseInt(editForm.batch_count),
        test_email: editForm.sending_mode === 'test' ? editForm.test_email : null,
        sending_mode: editForm.sending_mode,
        scheduled_at: scheduledTime.toISOString()
      })
      .eq('id', editingId);

    if (error) {
      toast.error("Failed to update campaign: " + error.message);
    } else {
      toast.success("Campaign updated successfully!");
      setEditingId(null);
      fetchCampaigns();
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to delete this scheduled campaign?")) return;
    
    const { error } = await supabase.from('scheduled_campaigns').delete().eq('id', id);
    if (error) {
      toast.error("Failed to delete campaign: " + error.message);
    } else {
      toast.success("Campaign deleted.");
      fetchCampaigns();
    }
  };

  const getStatusBadge = (status: string) => {
    switch(status) {
      case 'pending': return <span className="flex items-center text-amber-600 bg-amber-50 px-2 py-1 rounded-full text-[10px] font-bold uppercase"><Clock className="w-3 h-3 mr-1" /> Pending</span>;
      case 'processing': return <span className="flex items-center text-blue-600 bg-blue-50 px-2 py-1 rounded-full text-[10px] font-bold uppercase animate-pulse"><AlertCircle className="w-3 h-3 mr-1" /> Processing</span>;
      case 'completed': return <span className="flex items-center text-emerald-600 bg-emerald-50 px-2 py-1 rounded-full text-[10px] font-bold uppercase"><CheckCircle2 className="w-3 h-3 mr-1" /> Completed</span>;
      case 'failed': return <span className="flex items-center text-rose-600 bg-rose-50 px-2 py-1 rounded-full text-[10px] font-bold uppercase"><XCircle className="w-3 h-3 mr-1" /> Failed</span>;
      default: return <span className="text-zinc-500 bg-zinc-100 px-2 py-1 rounded-full text-[10px] font-bold uppercase">{status}</span>;
    }
  };

  return (
    <div className="space-y-8 max-w-6xl mx-auto pb-20">
      <div className="px-2">
        <h1 className="text-4xl font-bold text-zinc-900 tracking-tight flex items-center">
          <CalendarClock className="w-8 h-8 mr-3 text-blue-600" /> 
          Scheduler
        </h1>
        <p className="text-zinc-500 mt-2 text-sm font-medium">Monitor and manage your scheduled email campaigns.</p>
      </div>

      <div className="bg-white rounded-3xl shadow-xl border border-zinc-100 overflow-hidden flex flex-col min-h-[500px]">
        {/* Table Header */}
        <div className="p-6 border-b border-zinc-50 bg-zinc-50/50 flex justify-between items-center">
          <h2 className="font-bold text-zinc-900">Campaign History</h2>
          <Button onClick={fetchCampaigns} className="bg-zinc-200 text-zinc-800 hover:bg-zinc-300 px-3 py-1 text-xs rounded-xl h-8">Refresh</Button>
        </div>

        <div className="flex-1 overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="bg-zinc-50 border-b border-zinc-200 text-xs font-bold text-zinc-500 uppercase tracking-wider">
              <tr>
                <th className="p-4 w-48">Scheduled For</th>
                <th className="p-4">Template</th>
                <th className="p-4">Target</th>
                <th className="p-4">Mode</th>
                <th className="p-4 w-32">Status</th>
                <th className="p-4 w-24 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {isLoading ? (
                <tr><td colSpan={6} className="p-8 text-center text-zinc-400 font-medium">Loading campaigns...</td></tr>
              ) : campaigns.length === 0 ? (
                <tr><td colSpan={6} className="p-8 text-center text-zinc-400 font-medium">No scheduled campaigns found.</td></tr>
              ) : (
                campaigns.map((camp) => (
                  <React.Fragment key={camp.id}>
                    <tr className="hover:bg-zinc-50/50 transition-colors">
                      <td className="p-4 font-medium text-zinc-800">
                        {new Date(camp.scheduled_at).toLocaleString()}
                      </td>
                      <td className="p-4 text-zinc-600 font-medium">
                        {camp.templates?.title || 'Unknown Template'}
                      </td>
                      <td className="p-4">
                        <div className="text-xs font-bold text-zinc-700">{camp.target_table}</div>
                        {camp.sending_mode === 'batch' && (
                           <div className="text-[10px] text-zinc-500">Rows {camp.start_row} to {camp.start_row + camp.batch_count - 1}</div>
                        )}
                      </td>
                      <td className="p-4">
                        {camp.sending_mode === 'test' ? (
                           <span className="text-xs font-bold text-indigo-600 bg-indigo-50 px-2 py-1 rounded">Test</span>
                        ) : (
                           <span className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded">Batch</span>
                        )}
                      </td>
                      <td className="p-4">
                        {getStatusBadge(camp.status)}
                      </td>
                      <td className="p-4 text-right">
                        {camp.status === 'pending' && editingId !== camp.id && (
                          <div className="flex justify-end gap-2">
                            <button onClick={() => handleEditClick(camp)} className="p-2 text-zinc-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors" title="Edit">
                              <Edit2 className="w-4 h-4" />
                            </button>
                            <button onClick={() => handleDelete(camp.id)} className="p-2 text-zinc-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors" title="Delete">
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                    
                    {/* Inline Edit Form */}
                    {editingId === camp.id && (
                      <tr className="bg-blue-50/30 border-y-2 border-blue-100">
                        <td colSpan={6} className="p-6">
                          <div className="bg-white border border-blue-200 rounded-2xl p-6 shadow-sm relative">
                            <button onClick={handleCancelEdit} className="absolute top-4 right-4 p-1 text-zinc-400 hover:text-zinc-600 rounded-md">
                              <X className="w-5 h-5" />
                            </button>
                            
                            <h3 className="text-sm font-bold text-blue-900 mb-4 flex items-center">
                              <Edit2 className="w-4 h-4 mr-2" /> Edit Scheduled Campaign
                            </h3>
                            
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                              <div className="space-y-2">
                                <label className="text-xs font-bold text-zinc-500 uppercase">Scheduled Time</label>
                                <Input type="datetime-local" value={editForm.scheduled_at || ''} onChange={e => setEditForm({...editForm, scheduled_at: e.target.value})} className="bg-zinc-50" />
                              </div>
                              
                              <div className="space-y-2">
                                <label className="text-xs font-bold text-zinc-500 uppercase">Template</label>
                                <select className="w-full p-3 bg-zinc-50 border border-zinc-200 rounded-xl font-medium text-sm" value={editForm.template_id || ''} onChange={e => setEditForm({...editForm, template_id: e.target.value})}>
                                  {templates.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                                </select>
                              </div>
                              
                              <div className="space-y-2">
                                <label className="text-xs font-bold text-zinc-500 uppercase">Sending Mode</label>
                                <div className="flex bg-zinc-100 p-1 rounded-xl">
                                  <button onClick={() => setEditForm({...editForm, sending_mode: 'test'})} className={`flex-1 py-2 rounded-lg text-xs font-bold transition ${editForm.sending_mode === 'test' ? 'bg-white text-zinc-900 shadow-sm' : 'text-zinc-500'}`}>Test</button>
                                  <button onClick={() => setEditForm({...editForm, sending_mode: 'batch'})} className={`flex-1 py-2 rounded-lg text-xs font-bold transition ${editForm.sending_mode === 'batch' ? 'bg-zinc-900 text-white shadow-sm' : 'text-zinc-500'}`}>Batch</button>
                                </div>
                              </div>
                              
                              <div className="space-y-2">
                                <label className="text-xs font-bold text-zinc-500 uppercase">Target List</label>
                                <select className="w-full p-3 bg-zinc-50 border border-zinc-200 rounded-xl font-medium text-sm" value={editForm.target_table || ''} onChange={e => setEditForm({...editForm, target_table: e.target.value})}>
                                  <option value="members_list">BNP (members_list)</option>
                                  <option value="business_partners">B2B (business_partners)</option>
                                  <option value="customer_list">B2C (customer_list)</option>
                                </select>
                              </div>
                              
                              {editForm.sending_mode === 'test' ? (
                                <div className="space-y-2 md:col-span-2">
                                  <label className="text-xs font-bold text-zinc-500 uppercase">Test Email Address</label>
                                  <Input value={editForm.test_email || ''} onChange={e => setEditForm({...editForm, test_email: e.target.value})} className="bg-zinc-50" placeholder="recipient@example.com" />
                                </div>
                              ) : (
                                <div className="grid grid-cols-2 gap-4 md:col-span-2">
                                  <div className="space-y-2">
                                    <label className="text-xs font-bold text-zinc-500 uppercase">Start Row</label>
                                    <Input type="number" min="1" value={editForm.start_row || 1} onChange={e => setEditForm({...editForm, start_row: e.target.value})} className="bg-zinc-50" />
                                  </div>
                                  <div className="space-y-2">
                                    <label className="text-xs font-bold text-zinc-500 uppercase">Batch Count</label>
                                    <Input type="number" min="1" max="50" value={editForm.batch_count || 1} onChange={e => setEditForm({...editForm, batch_count: e.target.value})} className="bg-zinc-50" />
                                  </div>
                                </div>
                              )}
                            </div>
                            
                            <div className="mt-6 flex justify-end gap-3 pt-4 border-t border-blue-100">
                              <Button variant="outline" onClick={handleCancelEdit} className="border-zinc-200 text-zinc-600">Cancel</Button>
                              <Button onClick={handleSaveEdit} className="bg-blue-600 hover:bg-blue-700 text-white flex items-center">
                                <Save className="w-4 h-4 mr-2" /> Save Changes
                              </Button>
                            </div>
                          </div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default Scheduler;
