import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { useToast } from "@/components/ui/use-toast";
import {
  Clock, Calendar, Mail, Plus, Trash2, Edit2, Play, Pause,
  Coffee, Sun, Moon, FileText, Download, Bell, Send
} from "lucide-react";

const SCHEDULE_OPTIONS = [
  { value: 'daily', label: 'Daily', icon: Sun, description: 'Every morning at 7 AM' },
  { value: 'weekly', label: 'Weekly', icon: Calendar, description: 'Every Monday morning' },
  { value: 'biweekly', label: 'Bi-Weekly', icon: Calendar, description: 'Every other Monday' },
  { value: 'monthly', label: 'Monthly', icon: Calendar, description: 'First of each month' },
  { value: 'quarterly', label: 'Quarterly', icon: Calendar, description: 'Start of each quarter' },
];

const TIME_OPTIONS = [
  { value: '06:00', label: '6:00 AM - Early Bird' },
  { value: '07:00', label: '7:00 AM - First Coffee ☕' },
  { value: '08:00', label: '8:00 AM - Start of Day' },
  { value: '09:00', label: '9:00 AM - Morning' },
  { value: '12:00', label: '12:00 PM - Midday' },
  { value: '17:00', label: '5:00 PM - End of Day' },
];

export default function ScheduledReports({ userRole, scheduledReports = [], onUpdate }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingReport, setEditingReport] = useState(null);
  const [newSchedule, setNewSchedule] = useState({
    report_name: '',
    report_type: '',
    frequency: 'weekly',
    time: '07:00',
    recipients: '',
    format: 'pdf',
    is_active: true,
  });

  const createScheduleMutation = useMutation({
    mutationFn: async (scheduleData) => {
      // In real app, this would create a scheduled job
      // For now, we'll save it to user preferences
      await base44.auth.updateMe({
        scheduled_reports: [...(scheduledReports || []), { 
          ...scheduleData, 
          id: Date.now().toString(),
          created_at: new Date().toISOString()
        }]
      });
    },
    onSuccess: () => {
      toast({ title: "✅ Schedule Created", description: "Your report will be delivered automatically" });
      setShowCreateModal(false);
      setNewSchedule({ report_name: '', report_type: '', frequency: 'weekly', time: '07:00', recipients: '', format: 'pdf', is_active: true });
      onUpdate?.();
    },
  });

  const toggleScheduleMutation = useMutation({
    mutationFn: async ({ id, is_active }) => {
      const updated = scheduledReports.map(r => 
        r.id === id ? { ...r, is_active } : r
      );
      await base44.auth.updateMe({ scheduled_reports: updated });
    },
    onSuccess: () => {
      toast({ title: "Schedule Updated" });
      onUpdate?.();
    },
  });

  const deleteScheduleMutation = useMutation({
    mutationFn: async (id) => {
      const updated = scheduledReports.filter(r => r.id !== id);
      await base44.auth.updateMe({ scheduled_reports: updated });
    },
    onSuccess: () => {
      toast({ title: "Schedule Deleted" });
      onUpdate?.();
    },
  });

  const handleCreate = () => {
    if (!newSchedule.report_name || !newSchedule.recipients) {
      toast({ title: "Missing Fields", description: "Please fill in all required fields", variant: "destructive" });
      return;
    }
    createScheduleMutation.mutate(newSchedule);
  };

  const getFrequencyLabel = (freq) => {
    const option = SCHEDULE_OPTIONS.find(o => o.value === freq);
    return option?.label || freq;
  };

  const getNextDelivery = (schedule) => {
    const now = new Date();
    const [hours, minutes] = schedule.time.split(':').map(Number);
    const next = new Date(now);
    next.setHours(hours, minutes, 0, 0);
    
    if (next <= now) {
      switch (schedule.frequency) {
        case 'daily':
          next.setDate(next.getDate() + 1);
          break;
        case 'weekly':
          next.setDate(next.getDate() + (7 - now.getDay() + 1) % 7 || 7);
          break;
        default:
          next.setDate(next.getDate() + 1);
      }
    }
    
    return next.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
  };

  return (
    <div className="space-y-6">
      {/* Compact Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <Coffee className="w-5 h-5 text-[#0A39DF]" />
          <span className="font-semibold text-slate-900">Scheduled Reports</span>
          <span className="text-sm text-slate-500">— delivered like your morning coffee</span>
        </div>
        <Button onClick={() => setShowCreateModal(true)} size="sm" className="bg-[#0A39DF]">
          <Plus className="w-4 h-4 mr-1" />
          Schedule
        </Button>
      </div>

      {/* Compact Scheduled Reports List */}
      {scheduledReports?.length > 0 ? (
        <div className="space-y-2">
          {scheduledReports.map(schedule => (
            <div 
              key={schedule.id}
              className={`flex items-center gap-4 p-3 rounded-lg border ${schedule.is_active ? 'bg-white border-slate-200' : 'bg-slate-50 border-slate-100 opacity-60'}`}
            >
              <Switch
                checked={schedule.is_active}
                onCheckedChange={(checked) => toggleScheduleMutation.mutate({ id: schedule.id, is_active: checked })}
              />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-slate-900 truncate">{schedule.report_name}</span>
                  <Badge className="bg-purple-100 text-purple-700 text-[10px]">{getFrequencyLabel(schedule.frequency)}</Badge>
                  <Badge variant="outline" className="text-[10px]">{schedule.format?.toUpperCase()}</Badge>
                </div>
                <div className="flex items-center gap-3 text-xs text-slate-500 mt-1">
                  <span><Clock className="w-3 h-3 inline mr-1" />{schedule.time}</span>
                  <span className="truncate"><Mail className="w-3 h-3 inline mr-1" />{schedule.recipients}</span>
                  {schedule.is_active && <span className="text-emerald-600">Next: {getNextDelivery(schedule)}</span>}
                </div>
              </div>
              <div className="flex items-center gap-1">
                <Button size="sm" variant="ghost" className="h-7 px-2" onClick={() => { setEditingReport(schedule); setShowCreateModal(true); }}>
                  <Edit2 className="w-3 h-3" />
                </Button>
                <Button size="sm" variant="ghost" className="h-7 px-2 text-blue-600">
                  <Send className="w-3 h-3" />
                </Button>
                <Button size="sm" variant="ghost" className="h-7 px-2 text-red-600" onClick={() => deleteScheduleMutation.mutate(schedule.id)}>
                  <Trash2 className="w-3 h-3" />
                </Button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-8 text-slate-500">
          <Clock className="w-8 h-8 mx-auto mb-2 text-slate-300" />
          <p className="text-sm">No scheduled reports yet</p>
          <Button onClick={() => setShowCreateModal(true)} size="sm" variant="link" className="text-[#0A39DF]">
            Create your first schedule →
          </Button>
        </div>
      )}

      {/* Create/Edit Modal */}
      <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Calendar className="w-5 h-5 text-[#0A39DF]" />
              {editingReport ? 'Edit Schedule' : 'Create Report Schedule'}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium text-slate-700 mb-1 block">Report Name *</label>
              <Input
                value={newSchedule.report_name}
                onChange={(e) => setNewSchedule({ ...newSchedule, report_name: e.target.value })}
                placeholder="e.g., Weekly Labor Summary"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Frequency</label>
                <Select 
                  value={newSchedule.frequency} 
                  onValueChange={(v) => setNewSchedule({ ...newSchedule, frequency: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {SCHEDULE_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>
                        <div className="flex items-center gap-2">
                          <opt.icon className="w-4 h-4" />
                          {opt.label}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label className="text-sm font-medium text-slate-700 mb-1 block">Delivery Time</label>
                <Select 
                  value={newSchedule.time} 
                  onValueChange={(v) => setNewSchedule({ ...newSchedule, time: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {TIME_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 mb-1 block">Recipients *</label>
              <Input
                value={newSchedule.recipients}
                onChange={(e) => setNewSchedule({ ...newSchedule, recipients: e.target.value })}
                placeholder="email@company.com, another@company.com"
              />
              <p className="text-xs text-slate-500 mt-1">Separate multiple emails with commas</p>
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 mb-1 block">Format</label>
              <Select 
                value={newSchedule.format} 
                onValueChange={(v) => setNewSchedule({ ...newSchedule, format: v })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pdf">📄 PDF Document</SelectItem>
                  <SelectItem value="excel">📊 Excel Spreadsheet</SelectItem>
                  <SelectItem value="csv">📋 CSV File</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <p className="text-xs text-blue-800">
                <Coffee className="w-3 h-3 inline mr-1" />
                <strong>Pro Tip:</strong> 7 AM delivery ensures your report is ready with your morning coffee
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreateModal(false)}>Cancel</Button>
            <Button 
              onClick={handleCreate} 
              className="bg-[#0A39DF]"
              disabled={createScheduleMutation.isPending}
            >
              {createScheduleMutation.isPending ? 'Creating...' : 'Create Schedule'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}