import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
import { getAuth } from '@/auth';
import { useManageFeedbackContext } from '../hooks/useManageFeedbackMemberContext';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { X } from 'lucide-react';

const API_URL = apiConfig.service_feedback;

// Define status types
type StatusCode = 'W' | 'N' | 'Y';

// Status display mapping for Select component
const statusDisplayMap: Record<StatusCode, string> = {
  W: 'Waiting Follow Up',
  N: 'Rejected',
  Y: 'Accepted'
};

const EditDialog = () => {
  const [loading, setLoading] = useState(false);
  const { PutData, GetData } = useCallApi();
  const { handleEditDialog, showEditDialog, selectedFeedback, handleDetailDialog, refreshData } =
    useManageFeedbackContext();

  const [reviewNotes, setReviewNotes] = useState('');
  const [status, setStatus] = useState<StatusCode>('Y'); // Default to Accepted

  useEffect(() => {
    if (showEditDialog && selectedFeedback) {
      fetchFeedbackDetail();
    }
  }, [showEditDialog, selectedFeedback]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const username = getAuth()?.user.username;
      const payload = {
        review_by: username,
        review_notes: reviewNotes,
        status: status
      };

      const response = await PutData(`${API_URL}/feedback/update/${selectedFeedback}`, payload);

      if (response?.status) {
        toast.success('Feedback reviewed successfully');

        handleEditDialog(false, null);

        handleDetailDialog(false, null);

        refreshData();

        setTimeout(() => {
          handleDetailDialog(true, selectedFeedback);
        }, 300);
      } else {
        toast.error(response?.message || 'Failed to update feedback');
      }
    } catch (error) {
      console.error('Error updating feedback:', error);
      toast.error('An error occurred while updating feedback');
    } finally {
      setLoading(false);
    }
  };

  const fetchFeedbackDetail = async () => {
    if (!selectedFeedback) return;
    try {
      setLoading(true);
      const response = await GetData(`${API_URL}/feedback/detail/${selectedFeedback}`, {
        id: selectedFeedback
      });

      if (!response || !response.data) {
        console.error('Invalid response format');
        return;
      }

      const data = response.data;

      setReviewNotes(data.review_notes || '');

      const currentStatus = (data.status as StatusCode) || 'Y';
      setStatus(currentStatus);
    } catch (error) {
      console.error('Error fetching feedback details:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="p-0 w-full sm:max-w-2xl bg-white rounded-lg overflow-hidden [&>button]:hidden">
        <DialogHeader>
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <div className="relative">
          <div className="p-6 flex items-center justify-between border-b">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Review Feedback</h2>
              <p className="text-sm text-gray-500 mt-1">Review and update feedback status</p>
            </div>
            <button
              className="absolute right-6 top-6 text-gray-400 hover:text-gray-600"
              onClick={() => handleEditDialog(false, null)}
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          <form onSubmit={handleSubmit} className="p-6">
            <div className="space-y-6">
              <div className="space-y-4">
                <label className="block text-gray-700 text-lg">
                  Review Notes <span className="text-red-500">*</span>
                </label>
                <textarea
                  className="w-full min-h-48 p-4 text-gray-700 bg-white border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="Enter your review notes here..."
                  value={reviewNotes}
                  onChange={(e) => setReviewNotes(e.target.value)}
                  required
                />
              </div>

              <div className="space-y-4">
                <label className="block text-gray-700 text-lg">
                  Status <span className="text-red-500">*</span>
                </label>
                <Select
                  value={status}
                  onValueChange={(value: string) => setStatus(value as StatusCode)}
                >
                  <SelectTrigger className="w-full p-3 text-gray-700">
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Y">Accept</SelectItem>
                    <SelectItem value="N">Reject</SelectItem>
                    <SelectItem value="W">Waiting</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="flex justify-end gap-4 mt-8">
              <Button
                type="button"
                onClick={() => handleEditDialog(false, null)}
                disabled={loading}
                className="px-6 py-3 h-12 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-md"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={loading}
                className="px-6 py-3 h-12 bg-blue-600 hover:bg-blue-700 text-white rounded-md"
              >
                {loading ? 'Saving...' : 'Save Changes'}
              </Button>
            </div>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
