/* eslint-disable -- temporary disable for development/testing purposes */

import React, { useEffect, useState,useContext } from 'react';
import { Dialog,Alert, DialogTitle, DialogContent, DialogActions, Button, TextField, MenuItem, Select, FormControl, InputLabel, Typography ,} from '@mui/material';
import { UserContext } from '@/contexts/user-context';

interface VisitType {
  id: string;
  name: string;
}

interface AssignedRate {
  id: string; // visit_type_rates id
  visit_type_id: string;
  visit_type_name: string;
  rate: string;
}

interface DoctorRatesDialogProps {
  doctorId: string;
  open: boolean;
  onClose: () => void;
  onSaveSuccess?: () => void;
  onShowBanner?: (message: string, severity: 'success' | 'error') => void;
}

export default function DoctorRatesDialog({ doctorId, open, onClose, onSaveSuccess,  onShowBanner, }: DoctorRatesDialogProps) {
  const [assignedRates, setAssignedRates] = useState<AssignedRate[]>([]);
  const [unassignedTypes, setUnassignedTypes] = useState<VisitType[]>([]);
  const [newTypeId, setNewTypeId] = useState<string>('');
  const [newRate, setNewRate] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const currentUserId = loggedInUser?.id;
  const [response, setResponse] = useState<string | null>(null);
  const [bannerMessage, setBannerMessage] = useState<string | null>(null);
  const [bannerSeverity, setBannerSeverity] = useState<'success' | 'error' | 'warning' | 'info'>('success');
  const [loadingAssignedRates, setLoadingAssignedRates] = useState(true);

  const activeCompany = loggedInUser?.companies?.find(company => company.active);
  const companyId = activeCompany?.id;

  useEffect(() => {
    if (open) {
      fetchRatesAndTypes();
    }
  }, [open]);

  async function fetchRatesAndTypes() {
    setLoading(true);

    try {
      // Fetch assigned visit types and rates for this doctor
      const assignedRes = await fetch(`/admin/api/visit-type-rates/assigned?doctorId=${doctorId}&companyId=${companyId}`);
      const assignedData = await assignedRes.json();
  
      // console.log(doctorId, 'doctorId');
      // console.log(companyId, 'companyId');
      // console.log('assignedData:', assignedData);
  
      // Fetch all visit types for the company/manager or globally (modify as needed)
      const typesRes = await fetch(`/admin/api/visit-types?companyId=${companyId}`);
      const typesDataRaw = await typesRes.json();
  
      // console.log('typesDataRaw:', typesDataRaw);
  
      // Extract the array properly — adjust property name based on your API response
      // For example, if API returns { visitTypesWithRates: [...] } or { visitTypes: [...] }
      const visitTypes: VisitType[] =
        typesDataRaw.visitTypesWithRates ??
        typesDataRaw.visitTypes ??
        (Array.isArray(typesDataRaw) ? typesDataRaw : []);
  
      // console.log('visitTypes:', visitTypes);
  
      // Explicitly type assignedVisitTypes to AssignedRate[]
      const assignedTypes: AssignedRate[] = assignedData.assignedVisitTypes ?? [];
  
      // Extract assigned type ids and convert to number for comparison
      const assignedTypeIdsNum = assignedTypes.map(ar => Number(ar.visit_type_id));
      // console.log('assignedTypeIdsNum:', assignedTypeIdsNum);
  
      // Filter unassigned visit types by excluding assignedTypeIds
      const unassigned = visitTypes.filter(t => !assignedTypeIdsNum.includes(Number(t.id)));
  
      // Update state
      setAssignedRates(assignedTypes);
      setUnassignedTypes(unassigned);
      setNewTypeId('');
      setNewRate('');
    } catch (err) {
      console.error(err);
    }
    setLoading(false);
  }
  
  
  // Handle editing an existing rate
  function updateAssignedRate(id: string, newRateValue: string) {
    setAssignedRates(rates =>
      rates.map(r => (r.id === id ? { ...r, rate: newRateValue } : r))
    );
  }

  async function handleSave() {
    setLoading(true);
    setResponse(null); // Clear previous messages
  
    try {
      // Update existing assigned rates
      const updateResponses = await Promise.all(
        assignedRates.map(async (ar) => {
          const res = await fetch(`/admin/api/visit-type-rates/update`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              id: ar.id,
              rate: ar.rate,
            }),
          });
  
          const data = await res.json();
          return res.ok ? 'success' : data?.error || 'Update failed';
        })
      );
  
      let finalMessage = '';
      let finalSeverity: 'success' | 'error' = 'success';
  
      // Add new rate if provided
      if (newTypeId && newRate) {
        const res = await fetch(`/admin/api/visit-type-rates/update`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            doctor_id: doctorId,
            visit_type_id: newTypeId,
            rate: newRate,
            company_id: companyId,
            manager_id: currentUserId,
          }),
        });
  
        const data = await res.json();
  
        if (!res.ok) {
          finalMessage = data?.error || 'Failed to add new rate';
          finalSeverity = 'error';
        } else {
          finalMessage = 'Rate added successfully';
          finalSeverity = 'success';
        }
      } else {
        const hasFailure = updateResponses.some(resp => resp !== 'success');
        finalMessage = hasFailure ? 'Some updates failed' : 'Rates updated successfully';
        finalSeverity = hasFailure ? 'error' : 'success';
      }
  
      // Show banner BEFORE closing the dialog
      onShowBanner?.(finalMessage, finalSeverity);
  
      // Trigger callback and close dialog
      onSaveSuccess?.();
      onClose();
    } catch (err) {
      console.error('Error saving rates:', err);
      onShowBanner?.('An error occurred while saving', 'error');
    }
  
    setLoading(false);
  }
  

  return (
    <>
{bannerMessage && (
  <Alert severity={bannerSeverity} sx={{ mt: 2 }}>
    {bannerMessage}
  </Alert>
)}

    <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
      <DialogTitle>Manage Visit Type Rates</DialogTitle>
      <DialogContent>
        <Typography variant="h6">Existing</Typography>
      {loading ? (
  <Typography>Loading existing visit types...</Typography>
) : assignedRates.length === 0 ? (
  <Typography>No assigned types.</Typography>
) : (
  assignedRates.map((ar) => (
    <div key={ar.id} style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
      <Typography style={{ minWidth: 150 }}>{ar.visit_type_name}</Typography>
      <TextField
        label="Rate"
        value={ar.rate}
        onChange={e => updateAssignedRate(ar.id, e.target.value)}
        size="small"
        type="number"
        fullWidth
      />
    </div>
  ))
)}

        <Typography variant="h6" style={{ marginTop: 24 }}>
          Assign New Visit Type
        </Typography>
        <FormControl fullWidth margin="normal">
          <InputLabel id="new-type-label">Visit Type</InputLabel>
          <Select
            labelId="new-type-label"
            value={newTypeId}
            label="Visit Type"
            onChange={e => setNewTypeId(e.target.value)}
          >
            {unassignedTypes.map(t => (
              <MenuItem key={t.id} value={t.id}>{t.name}</MenuItem>
            ))}
          </Select>
        </FormControl>
        {newTypeId && (
          <TextField
            label="Rate"
            value={newRate}
            onChange={e => setNewRate(e.target.value)}
            type="number"
            fullWidth
            margin="normal"
            size="small"
          />
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>Cancel</Button>
        <Button onClick={handleSave} disabled={loading || (!newTypeId && assignedRates.length === 0)}>
          Save
        </Button>
      </DialogActions>
    </Dialog>
    </>
  );
}
