import { useForm } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import { Textarea } from '@/Components/ui/textarea';
import { trackProductEvent } from '@/lib/analytics';
import { RECOMMENDATION_APPLIED } from '@/lib/event-catalog';

interface StatusChangeModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  siteId: number;
  recommendationId: number;
  currentStatus: string;
}

const STATUS_OPTIONS = [
  { value: 'pending', label: 'Pending' },
  { value: 'reviewed', label: 'Reviewed' },
  { value: 'approved', label: 'Approved' },
  { value: 'rejected', label: 'Rejected' },
  { value: 'deferred', label: 'Deferred' },
  { value: 'applied', label: 'Applied' },
  { value: 'tracking', label: 'Tracking' },
];

export default function StatusChangeModal({
  open,
  onOpenChange,
  siteId,
  recommendationId,
  currentStatus,
}: StatusChangeModalProps) {
  const { data, setData, patch, processing, errors } = useForm({
    lifecycle_status: currentStatus,
    status_notes: '',
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    patch(route('recommendations.update-status', [siteId, recommendationId]), {
      onSuccess: () => {
        trackProductEvent('recommendation_status_changed', {
          recommendation_id: recommendationId,
          new_status: data.lifecycle_status,
          site_id: siteId,
        });
        if (data.lifecycle_status === 'applied') {
          trackProductEvent(RECOMMENDATION_APPLIED, {
            site_id: siteId,
            recommendation_id: recommendationId,
          });
        }
        onOpenChange(false);
      },
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Change Recommendation Status</DialogTitle>
          <DialogDescription>
            Update the lifecycle status of this recommendation and add optional notes.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="lifecycle_status">Status</Label>
            <Select
              value={data.lifecycle_status}
              onValueChange={(val) => setData('lifecycle_status', val)}
            >
              <SelectTrigger id="lifecycle_status">
                <SelectValue placeholder="Select a status" />
              </SelectTrigger>
              <SelectContent>
                {STATUS_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {errors.lifecycle_status && (
              <p className="text-sm text-destructive">{errors.lifecycle_status}</p>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="status_notes">Notes (optional)</Label>
            <Textarea
              id="status_notes"
              value={data.status_notes}
              onChange={(e) => setData('status_notes', e.target.value)}
              placeholder="Add any notes about this status change..."
              className="min-h-[100px]"
              aria-invalid={!!errors.status_notes}
              aria-describedby={errors.status_notes ? 'status_notes-error' : undefined}
            />
            {errors.status_notes && (
              <p id="status_notes-error" className="text-sm text-destructive">
                {errors.status_notes}
              </p>
            )}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <LoadingButton loading={processing} loadingText="Updating...">
              Update Status
            </LoadingButton>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
