import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

const TIMELINE_STAGES = ["First Notice", "Second Notice", "Third & Final Notice", "Fined", "Resolved", "Escalated", "Owner Response", "Legal Action", "Other"];

export default function ViolationTimelineEntryDialog({ open, onOpenChange, entry, onSave, loading }) {
  const [formData, setFormData] = useState({ date: new Date().toISOString().split('T')[0], stage: 'Other', description: '' });

  useEffect(() => {
    if (entry) { setFormData({ date: entry.date || new Date().toISOString().split('T')[0], stage: entry.stage || 'Other', description: entry.description || '' }); }
    else { setFormData({ date: new Date().toISOString().split('T')[0], stage: 'Other', description: '' }); }
  }, [entry, open]);

  const handleSubmit = (e) => { e.preventDefault(); onSave(formData); };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader><DialogTitle>{entry ? 'Edit Timeline Entry' : 'Add Timeline Entry'}</DialogTitle></DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2"><Label>Date</Label><Input type="date" value={formData.date} onChange={(e) => setFormData(p => ({ ...p, date: e.target.value }))} required /></div>
            <div className="space-y-2"><Label>Event Type</Label>
              <Select value={formData.stage} onValueChange={(val) => setFormData(p => ({ ...p, stage: val }))}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>{TIMELINE_STAGES.map(s => (<SelectItem key={s} value={s}>{s}</SelectItem>))}</SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2"><Label>Description</Label><Textarea value={formData.description} onChange={(e) => setFormData(p => ({ ...p, description: e.target.value }))} rows={4} required /></div>
          <DialogFooter><Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button><Button type="submit" disabled={loading}>{loading ? 'Saving...' : 'Save'}</Button></DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
