import { useState, useEffect } from 'react';
import {
  Card, Box, Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
  Typography, TextField, Button, Dialog, DialogTitle, DialogContent, DialogActions,
  Grid, IconButton, CircularProgress, Chip, MenuItem, InputAdornment, alpha, Autocomplete, Checkbox, FormControlLabel, Tabs, Tab, Snackbar, Alert
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import SearchIcon from '@mui/icons-material/Search';
import CloseIcon from '@mui/icons-material/Close';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';

import PageHeader from '@/components/PageHeader';
import { fetchClients } from '@/utils/apiClient';
import ClientFormDialog from '../tenants/ClientFormDialog';

const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.doormile.com/api/v1';

const CITIES = [
  'Chennai', 'Coimbatore', 'Madurai', 'Tiruchirappalli', 'Salem', 'Tuticorin', 'Tirupur', 'Erode', 'Vellore', 'Tirunelveli', 'Thanjavur', 'Dindigul', 'Hosur', 'Nagercoil', 'Karur', 'Namakkal', 'Kanchipuram', 'Cuddalore', 'Thoothukudi',
  'Bengaluru', 'Mysuru', 'Mangaluru', 'Hubli', 'Belagavi', 'Kalaburagi', 'Davangere', 'Ballari',
  'Kochi', 'Thiruvananthapuram', 'Kozhikode', 'Kannur', 'Thrissur', 'Kollam',
  'Hyderabad', 'Warangal', 'Visakhapatnam', 'Vijayawada', 'Tirupati', 'Guntur', 'Rajahmundry', 'Nellore',
  'Mumbai', 'Pune', 'Nagpur', 'Nashik', 'Aurangabad', 'Kolhapur', 'Solapur',
  'New Delhi', 'Gurugram', 'Noida', 'Faridabad', 'Chandigarh', 'Amritsar', 'Ludhiana', 'Jalandhar',
  'Ahmedabad', 'Surat', 'Vadodara', 'Rajkot', 'Bhavnagar', 'Jamnagar',
  'Kolkata', 'Howrah', 'Durgapur', 'Asansol', 'Siliguri',
  'Lucknow', 'Kanpur', 'Agra', 'Varanasi', 'Allahabad', 'Meerut',
  'Bhopal', 'Indore', 'Gwalior', 'Jabalpur',
  'Jaipur', 'Jodhpur', 'Udaipur', 'Kota', 'Bikaner',
  'Patna', 'Gaya', 'Bhagalpur',
  'Bhubaneswar', 'Cuttack', 'Rourkela',
  'Guwahati', 'Raipur', 'Ranchi', 'Dehradun'
];

const getHeaders = () => {
  const token = localStorage.getItem('auth_token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
};

async function apiFetchBookings() {
  const res = await fetch(`${API_BASE}/admin/bookings`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch bookings');
  const json = await res.json();
  return Array.isArray(json) ? json : (json.data || []);
}

async function apiFetchSurveys() {
  const res = await fetch(`${API_BASE}/admin/competitor-branches?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch surveys');
  const json = await res.json();
  return Array.isArray(json) ? json : (json.data || []);
}

async function apiCreateBooking(payload) {
  const res = await fetch(`${API_BASE}/admin/crmbooking`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(payload)
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || 'Failed to create booking');
  }
  return res.json();
}

function BookingFormDialog({ open, onClose, onSave, clients, surveys }) {
  const [clientDialogOpen, setClientDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    customer_name: '',
    customer_phone: '',
    pickupaddress: '',
    pickuppincode: '',
    deliveryaddress: '',
    deliverypincode: '',
    deliverycity: '',
    providercompany: '',
    providerlocation: '',
    notes: '',
    service_option: 'Normal',
    finalprice: '',
    insuranceamount: '',
    needsinsurance: false,
    declaredvalue: '',
    parcels: [{ itemcategory: '', weight: '', length: '', width: '', height: '' }]
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [quoteInfo, setQuoteInfo] = useState(null);

  useEffect(() => {
    if (open) {
      setFormData({
        customer_name: '',
        customer_phone: '',
        pickupaddress: '',
        pickuppincode: '',
        deliveryaddress: '',
        deliverypincode: '',
        deliverycity: '',
        providercompany: '',
        providerlocation: '',
        notes: '',
        service_option: 'Normal',
        finalprice: '',
        insuranceamount: '',
        needsinsurance: false,
        declaredvalue: '',
        parcels: [{ itemcategory: '', weight: '', length: '', width: '', height: '' }]
      });
      setError(null);
      setQuoteInfo(null);
    }
  }, [open]);

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

  const handleParcelChange = (index, field) => (e) => {
    const newParcels = [...formData.parcels];
    newParcels[index] = { ...newParcels[index], [field]: e.target.value };
    setFormData(prev => ({ ...prev, parcels: newParcels }));
  };

  const addParcel = () => {
    setFormData(prev => ({
      ...prev,
      parcels: [...prev.parcels, { itemcategory: '', weight: '', length: '', width: '', height: '' }]
    }));
  };

  const removeParcel = (index) => {
    if (formData.parcels.length <= 1) return;
    const newParcels = [...formData.parcels];
    newParcels.splice(index, 1);
    setFormData(prev => ({ ...prev, parcels: newParcels }));
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      if (!formData.pickupaddress || !formData.pickuppincode) {
        throw new Error('Pickup Address and Pincode are required');
      }

      const payload = {
        ...formData,
        finalprice: parseFloat(formData.finalprice) || 0,
        insuranceamount: parseFloat(formData.insuranceamount) || 0,
        parcels: formData.parcels.map(p => ({
          itemcategory: p.itemcategory || 'General',
          weight: parseFloat(p.weight) || 1.0,
          length: parseFloat(p.length) || 1.0,
          width: parseFloat(p.width) || 1.0,
          height: parseFloat(p.height) || 1.0,
        }))
      };

      await apiCreateBooking(payload);
      onSave();
      onClose();
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to create booking');
    } finally {
      setSaving(false);
    }
  };

  const handleCheckPrice = async () => {
    try {
      const res = await fetch(`${API_BASE}/admin/pricing/quote`, {
        method: 'POST',
        headers: getHeaders(),
        body: JSON.stringify({
          parcels: formData.parcels.map(p => ({
            weight: parseFloat(p.weight) || 1.0,
            length: parseFloat(p.length) || 1.0,
            width: parseFloat(p.width) || 1.0,
            height: parseFloat(p.height) || 1.0,
          }))
        })
      });
      if (res.ok) {
        const data = await res.json();
        setQuoteInfo(data);
        if (!formData.finalprice) {
          setFormData(prev => ({ ...prev, finalprice: data.basequote?.toFixed(2) || '' }));
        }
      }
    } catch(e) { console.error(e); }
  };

  const uniqueProviders = Array.from(new Set(surveys.map(s => s.company).filter(Boolean)));
  const providerLocations = surveys.filter(s => s.company === formData.providercompany).map(s => s.area || s.address).filter(Boolean);

  return (
    <>
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        sx={{ zIndex: 9999 }}
      >
        <Alert onClose={() => setError(null)} severity="error" variant="filled" sx={{ width: '100%', boxShadow: 3 }}>
          {error}
        </Alert>
      </Snackbar>

      <Dialog open={open} onClose={saving ? undefined : onClose} maxWidth="md" fullWidth>
        <DialogTitle sx={{ fontWeight: 800 }}>Create New Booking</DialogTitle>
        <DialogContent dividers>
        <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1, color: 'primary.main' }}>Customer Details</Typography>
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12}>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              <Autocomplete
                options={clients}
                sx={{ flexGrow: 1 }}
                getOptionLabel={(option) => {
                  if (typeof option === 'string') return option;
                  return `${option.first_name || ''} ${option.last_name || ''} - ${option.phone || ''}`;
                }}
                onChange={(e, newValue) => {
                  if (newValue && typeof newValue === 'object') {
                    setFormData(prev => ({
                      ...prev,
                      customer_name: `${newValue.first_name || ''} ${newValue.last_name || ''}`.trim(),
                      customer_phone: newValue.phone || ''
                    }));
                  } else {
                    setFormData(prev => ({ ...prev, customer_name: '', customer_phone: '' }));
                  }
                }}
                renderInput={(params) => (
                  <TextField {...params} label="Select Existing Client" size="small" />
                )}
              />
              <Button variant="outlined" startIcon={<AddIcon />} onClick={() => setClientDialogOpen(true)} sx={{ whiteSpace: 'nowrap' }}>
                New Client
              </Button>
            </Box>
          </Grid>
        </Grid>

        <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1, color: 'primary.main' }}>Assigned Provider (From Survey)</Typography>
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              options={uniqueProviders}
              value={formData.providercompany}
              onChange={(e, val) => setFormData(prev => ({ ...prev, providercompany: val || '', providerlocation: '' }))}
              renderInput={(params) => <TextField {...params} label="Provider Name" size="small" />}
            />
          </Grid>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              options={providerLocations}
              value={formData.providerlocation}
              onChange={(e, val) => setFormData(prev => ({ ...prev, providerlocation: val || '' }))}
              renderInput={(params) => <TextField {...params} label="Provider Location / Sub Hub" size="small" />}
              disabled={!formData.providercompany}
            />
          </Grid>
        </Grid>

        <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1, color: 'primary.main' }}>Pickup Location</Typography>
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={8}>
            <TextField fullWidth label="Pickup Address *" value={formData.pickupaddress} onChange={handleChange('pickupaddress')} size="small" />
          </Grid>
          <Grid item xs={12} sm={4}>
            <TextField fullWidth label="Pickup Pincode *" value={formData.pickuppincode} onChange={handleChange('pickuppincode')} size="small" />
          </Grid>
        </Grid>

        <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1, color: 'primary.main' }}>Delivery Destination</Typography>
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={12}>
            <TextField fullWidth label="Delivery Address" value={formData.deliveryaddress} onChange={handleChange('deliveryaddress')} size="small" />
          </Grid>
          <Grid item xs={12} sm={8}>
            <Autocomplete
              freeSolo
              options={CITIES}
              value={formData.deliverycity}
              onChange={(e, val) => setFormData(prev => ({ ...prev, deliverycity: val || '' }))}
              onInputChange={(e, val) => setFormData(prev => ({ ...prev, deliverycity: val || '' }))}
              renderInput={(params) => <TextField {...params} label="Search City" size="small" />}
            />
          </Grid>
          <Grid item xs={12} sm={4}>
            <TextField fullWidth label="Delivery Pincode" value={formData.deliverypincode} onChange={handleChange('deliverypincode')} size="small" />
          </Grid>
        </Grid>

        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 700, color: 'primary.main' }}>Parcel Details</Typography>
          <Button size="small" startIcon={<AddIcon />} onClick={addParcel}>Add Parcel</Button>
        </Box>
        
        {formData.parcels.map((parcel, idx) => (
          <Grid container spacing={1.5} key={idx} sx={{ mb: 2, alignItems: 'center' }}>
            <Grid item xs={12} sm={3}>
              <TextField fullWidth label="Category (e.g. Box)" value={parcel.itemcategory} onChange={handleParcelChange(idx, 'itemcategory')} size="small" />
            </Grid>
            <Grid item xs={6} sm={2}>
              <TextField fullWidth label="Weight (kg)" type="number" value={parcel.weight} onChange={handleParcelChange(idx, 'weight')} size="small" />
            </Grid>
            <Grid item xs={6} sm={2}>
              <TextField fullWidth label="Length (cm)" type="number" value={parcel.length} onChange={handleParcelChange(idx, 'length')} size="small" />
            </Grid>
            <Grid item xs={6} sm={2}>
              <TextField fullWidth label="Width (cm)" type="number" value={parcel.width} onChange={handleParcelChange(idx, 'width')} size="small" />
            </Grid>
            <Grid item xs={4} sm={2}>
              <TextField fullWidth label="Height (cm)" type="number" value={parcel.height} onChange={handleParcelChange(idx, 'height')} size="small" />
            </Grid>
            <Grid item xs={2} sm={1}>
              <IconButton color="error" onClick={() => removeParcel(idx)} disabled={formData.parcels.length === 1}>
                <DeleteOutlineIcon />
              </IconButton>
            </Grid>
          </Grid>
        ))}

        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mt: 2, mb: 1 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 700, color: 'primary.main' }}>Price & Insurance</Typography>
          <Button size="small" variant="outlined" onClick={handleCheckPrice}>Check Price Estimate</Button>
        </Box>
        {quoteInfo && (
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2, px: 1, borderLeft: '4px solid #3b82f6', bgcolor: '#eff6ff', py: 1 }}>
            Estimated Base Price: <strong>₹{quoteInfo.basequote?.toFixed(2)}</strong> (Chargeable Weight: {quoteInfo.chargeableweight} kg)
          </Typography>
        )}
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={3}>
            <TextField fullWidth label="Final Price (₹)" type="number" value={formData.finalprice} onChange={handleChange('finalprice')} size="small" />
          </Grid>
          <Grid item xs={12} sm={9}>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              <FormControlLabel 
                control={<Checkbox checked={formData.needsinsurance} onChange={(e) => {
                   const checked = e.target.checked;
                   setFormData(prev => ({
                     ...prev, 
                     needsinsurance: checked,
                     insuranceamount: checked && prev.declaredvalue ? (parseFloat(prev.declaredvalue) * 0.01).toFixed(2) : prev.insuranceamount
                   }));
                }} />} 
                label="Needs Insurance? (1%)" 
                sx={{ whiteSpace: 'nowrap' }}
              />
              <TextField 
                label="Declared Value (₹)" 
                type="number" 
                size="small" 
                sx={{ width: 150 }}
                value={formData.declaredvalue} 
                onChange={(e) => {
                  const val = e.target.value;
                  setFormData(prev => ({
                    ...prev,
                    declaredvalue: val,
                    insuranceamount: prev.needsinsurance && val ? (parseFloat(val) * 0.01).toFixed(2) : prev.insuranceamount
                  }));
                }} 
              />
              <TextField 
                label="Insurance Amount (₹)" 
                type="number" 
                size="small" 
                sx={{ width: 150 }}
                value={formData.insuranceamount} 
                onChange={handleChange('insuranceamount')} 
              />
            </Box>
          </Grid>
        </Grid>

        <Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1, color: 'primary.main' }}>Additional Information</Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={6}>
            <TextField select fullWidth label="Select Speed" value={formData.service_option} onChange={handleChange('service_option')} size="small">
              <MenuItem value="Normal">Normal</MenuItem>
              <MenuItem value="Fast">Fast Express</MenuItem>
            </TextField>
          </Grid>
          <Grid item xs={12} sm={6}>
            <TextField fullWidth label="Notes / Remarks" value={formData.notes} onChange={handleChange('notes')} size="small" />
          </Grid>
        </Grid>

      </DialogContent>
      <DialogActions sx={{ p: 2 }}>
        <Button onClick={onClose} disabled={saving}>Cancel</Button>
        <Button variant="contained" onClick={handleSave} disabled={saving || !formData.customer_phone} sx={{ bgcolor: 'primary.main', '&:hover': { bgcolor: 'primary.dark' } }}>
          {saving ? 'Creating...' : 'Create Booking'}
        </Button>
      </DialogActions>
    </Dialog>
      {/* Embedded Client Registration Form */}
      {clientDialogOpen && (
        <ClientFormDialog
          open={clientDialogOpen}
          mode="create"
          onClose={() => setClientDialogOpen(false)}
          onSaved={() => {
            setClientDialogOpen(false);
            onSave(); // Refetch clients so they appear in dropdown
          }}
        />
      )}
    </>
  );
}

export default function Bookings() {
  const [bookings, setBookings] = useState([]);
  const [clients, setClients] = useState([]);
  const [surveys, setSurveys] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [sourceFilter, setSourceFilter] = useState('All');
  const [formOpen, setFormOpen] = useState(false);

  const loadData = async () => {
    setLoading(true);
    try {
      const [bookingsData, clientsData, surveysData] = await Promise.all([
        apiFetchBookings(),
        fetchClients().catch(() => []),
        apiFetchSurveys().catch(() => [])
      ]);
      setBookings(Array.isArray(bookingsData) ? bookingsData : []);
      setClients(Array.isArray(clientsData) ? clientsData : []);
      setSurveys(Array.isArray(surveysData) ? surveysData : []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const displayBookings = bookings.filter(b => {
    const matchesSearch = (b.bookingno || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.pickupaddress || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.deliverycity || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.providercompany || '').toLowerCase().includes(search.toLowerCase());
    const matchesSource = sourceFilter === 'All' || b.bookingsource === sourceFilter;
    return matchesSearch && matchesSource;
  });

  return (
    <Box sx={{ p: 3, bgcolor: '#f8fafc', minHeight: '80vh' }}>
      <PageHeader title="Bookings Management" breadcrumbs={[{ label: 'Bookings' }]} />

      <Card sx={{ mt: 3, p: 3, borderRadius: 4, boxShadow: '0 12px 24px -4px rgba(0,0,0,0.05)' }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
          <TextField
            placeholder="Search bookings..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            size="small"
            InputProps={{
              startAdornment: <InputAdornment position="start"><SearchIcon /></InputAdornment>,
              sx: { borderRadius: 3, bgcolor: alpha('#e2e8f0', 0.4) }
            }}
          />
          <Button variant="contained" startIcon={<AddIcon />} onClick={() => setFormOpen(true)} sx={{ borderRadius: 2 }}>
            New Booking
          </Button>
        </Box>

        <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
          <Tabs value={sourceFilter} onChange={(e, val) => setSourceFilter(val)} aria-label="booking source filter tabs">
            <Tab label="All Bookings" value="All" />
            <Tab label="App Bookings" value="Customer_App" />
            <Tab label="CRM Bookings" value="CRM_Console" />
          </Tabs>
        </Box>

        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}><CircularProgress /></Box>
        ) : (
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow sx={{ bgcolor: alpha('#f1f5f9', 0.6) }}>
                  <TableCell sx={{ fontWeight: 700 }}>Booking No</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Delivery City</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Provider</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Source</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Price</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Status</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {displayBookings.length === 0 ? (
                  <TableRow><TableCell colSpan={6} align="center" sx={{ py: 4 }}>No bookings found.</TableCell></TableRow>
                ) : (
                  displayBookings.map(b => (
                    <TableRow key={b.bookingid} hover>
                      <TableCell sx={{ fontWeight: 600 }}>{b.bookingno}</TableCell>
                      <TableCell>{b.deliverycity || b.deliverypincode || 'N/A'}</TableCell>
                      <TableCell>
                        {b.providercompany ? (
                          <Chip label={b.providercompany} size="small" sx={{ mr: 1 }} />
                        ) : 'N/A'}
                      </TableCell>
                      <TableCell>
                        <Chip label={b.bookingsource === 'CRM_Console' ? 'CRM' : 'App'} size="small" variant="outlined" color={b.bookingsource === 'CRM_Console' ? 'secondary' : 'primary'} />
                      </TableCell>
                      <TableCell>
                        {b.serviceoptions && b.serviceoptions.length > 0 ? `₹${b.serviceoptions[0].estimatedprice}` : 'N/A'}
                      </TableCell>
                      <TableCell>
                        <Chip label={b.status} size="small" color={b.status === 'Pending_Pickup' ? 'warning' : 'primary'} />
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Card>

      <BookingFormDialog 
        open={formOpen} 
        onClose={() => setFormOpen(false)} 
        onSave={() => { loadData(); }}
        clients={clients}
        surveys={surveys}
      />
    </Box>
  );
}
