
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { Loader2, Save, Trash2, CheckCircle2 } from 'lucide-react';
import { format } from 'date-fns';

export default function ReminderDialog({ open, onOpenChange, reminder, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  
  const [formData, setFormData] = useState({
    title: '', description: '', due_date: '', assigned_to: '', priority: 'medium', status: 'pending'
  });

  useEffect(() => { fetchUsers(); }, []);

  useEffect(() => {
    if (open) {
      if (reminder) {
        setFormData({
          title: reminder.title || '', description: reminder.description || '',
          due_date: reminder.due_date ? format(new Date(reminder.due_date), 'yyyy-MM-dd HH:mm') : '',
          assigned_to: reminder.assigned_to || '', priority: reminder.priority || 'medium', status: reminder.status || 'pending'
        });
      } else {
        const nextHour = new Date();
        nextHour.setHours(nextHour.getHours() + 1);
        nextHour.setMinutes(0);
        setFormData({
          title: '', description: '', due_date: format(nextHour, 'yyyy-MM-dd HH:mm'),
          assigned_to: user?.id || '', priority: 'medium', status: 'pending'
        });
      }
    }
  }, [open, reminder, user]);

  const fetchUsers = async () => {
    const { data } = await supabase.from('profiles').select('id, email, full_name').order('email');
    if (data) setUsers(data);
  };

  const handleChange = (field, value) => setFormData(prev => ({ ...prev, [field]: value }));

  const handleSubmit = async () => {
    if (!formData.title.trim()) { toast({ variant: "destructive", title: "Required", description: "Title is required." }); return; }
    if (!formData.due_date) { toast({ variant: "destructive", title: "Required", description: "Due date is required." }); return; }

    setLoading(true);
    try {
      const payload = {
        title: formData.title, description: formData.description,
        due_date: new Date(formData.due_date).toISOString(),
        assigned_to: formData.assigned_to, priority: formData.priority,
        status: formData.status, updated_at: new Date().toISOString()
      };
      if (!reminder) { payload.created_by = user.id; payload.created_at = new Date().toISOString(); }

      let error;
      if (reminder?.id) {
        const { error: updateError } = await supabase.from('reminders').update(payload).eq('id', reminder.id);
        error = updateError;
      } else {
        const { error: insertError } = await supabase.from('reminders').insert([payload]);
        error = insertError;
      }
      if (error) throw error;
      toast({ title: "Success", description: reminder ? "Reminder updated." : "Reminder created." });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error(error);
      toast({ variant: "destructive", title: "Error", description: error.message });
    } finally { setLoading(false); }
  };

  const handleDelete = async () => {
    if (!confirm("Are you sure you want to delete this reminder?")) return;
    setLoading(true);
    try {
      const { error } = await supabase.from('reminders').delete().eq('id', reminder.id);
      if (error) throw error;
      toast({ title: "Deleted", description: "Reminder removed." });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (e) {
      toast({ variant: "destructive", title: "Error", description: e.message });
    } finally { setLoading(false); }
  };

  const handleMarkComplete = async () => {
    setLoading(true);
    try {
      const { error } = await supabase.from('reminders')
        .update({ status: 'completed', updated_at: new Date().toISOString() })
        .eq('id', reminder.id);
      if (error) throw error;
      toast({ title: "Completed", description: "Reminder marked as complete." });
      if (onSuccess) onSuccess();
      onOpenChange(false);
    } catch (e) {
      toast({ variant: "destructive", title: "Error", description: e.message });
    } finally { setLoading(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{reminder ? "Edit Reminder" : "Create Reminder"}</DialogTitle>
          <DialogDescription>Set a reminder details, priority and assignment.</DialogDescription>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="title">Title *</Label>
            <Input id="title" value={formData.title} onChange={(e) => handleChange('title', e.target.value)} placeholder="e.g. Follow up on violation" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea id="description" value={formData.description} onChange={(e) => handleChange('description', e.target.value)} placeholder="Add details..." rows={3} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="due_date">Due Date *</Label>
              <Input id="due_date" type="datetime-local" value={formData.due_date} onChange={(e) => handleChange('due_date', e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="priority">Priority</Label>
              <Select value={formData.priority} onValueChange={(val) => handleChange('priority', val)}>
                <SelectTrigger id="priority"><SelectValue placeholder="Select Priority" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">Low</SelectItem>
                  <SelectItem value="medium">Medium</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="assigned_to">Assign To</Label>
            <Select value={formData.assigned_to} onValueChange={(val) => handleChange('assigned_to', val)}>
              <SelectTrigger id="assigned_to"><SelectValue placeholder="Select User" /></SelectTrigger>
              <SelectContent>
                {users.map(u => (<SelectItem key={u.id} value={u.id}>{u.full_name || u.email}</SelectItem>))}
              </SelectContent>
            </Select>
          </div>
          {reminder && (
            <div className="text-xs text-muted-foreground pt-2 border-t mt-2">
              Created: {format(new Date(reminder.created_at), 'PPP p')}
            </div>
          )}
        </div>

        <DialogFooter className="flex items-center sm:justify-between w-full gap-2">
          <div className="flex items-center gap-2">
            {reminder && (
              <>
                <Button variant="ghost" className="text-destructive hover:text-destructive hover:bg-destructive/10" onClick={handleDelete} type="button">
                  <Trash2 className="w-4 h-4 mr-2" /> Delete
                </Button>
                <Button variant="outline" className="text-emerald-600 border-emerald-200 hover:bg-emerald-50" onClick={handleMarkComplete} type="button">
                  <CheckCircle2 className="w-4 h-4 mr-2" /> Complete
                </Button>
              </>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={() => onOpenChange(false)} type="button">Cancel</Button>
            <Button onClick={handleSubmit} disabled={loading}>
              {loading && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
              <Save className="w-4 h-4 mr-2" /> Save
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
