import { useState, useEffect } from 'react';
import {
  Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid, TextField,
  MenuItem, Box, Typography, Divider, Alert, CircularProgress, IconButton, Autocomplete, Snackbar, useMediaQuery
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import CloseIcon from '@mui/icons-material/Close';
import MyLocationIcon from '@mui/icons-material/MyLocation';
import { createClient, updateClient } from '@/utils/apiClient';

const BUSINESS_TYPES = ['retail', 'wholesale', 'manufacturer', 'distributor', 'services', 'ecommerce', 'other'];
const STATUSES = ['newClient', 'contacted', 'onboarded', 'lost'];
const FREQUENCIES = ['Daily', 'Weekly', 'Bi-weekly', 'Monthly', 'On-demand'];
const CONSENTS = ['basicOnly', 'full', 'none'];

const PROVIDERS = [
  'Blue Dart', 'Delhivery', 'DTDC', 'India Post / Speed Post', 'The Professional Couriers', 'XpressBees', 'Ecom Express', 'Shadowfax',
  'Safexpress', 'VRL Logistics', 'TCI (Transport Corporation of India)', 'Om Logistics', 'Best Roadways',
  'MSS (Mettur Super Services)', 'ABT Travels & Logistics', 'Navata Road Transport', 'KRS (Kerala Roadways)', 'Parveen Travels / Parveen Express', 'SRM Transports', 'KPN Travels & KPN Speed Parcel', 'SRS Travels',
  'Hindusthan Travels', 'City Travels', 'Essaar Travels', 'No. 1 Air Travels', 'A1 Travels', 'Krish Travels', 'Hebron Transports', 'Horma Travels', 'Vivegam Travels', 'PSS Transport', 'SRT (Renugambal Travels)', 'Thamarai Bus Transports', 'Rathimeena Travels', 'Ganesh Travels', 'John Kennedy Bus Service', 'Arun Travel', 'Saaji Meera Roadways', 'ARC Parcel Service', 'Chakra Travels & Parcel Service', 'MVA Parcel And Bus Service',
  'Shrinath Travels & Cargo', 'Hans Travels', 'Zingbus', 'Kalpana Travels / City Land Travels', 'Trackon Couriers', 'North India Transways', 'RSRTC Cargo', 'UPSRTC Cargo'
];

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',
  'Jaipur', 'Jodhpur', 'Udaipur', 'Kota', 'Bikaner',
  'Lucknow', 'Kanpur', 'Varanasi', 'Agra', 'Prayagraj', 'Gorakhpur', 'Bhopal', 'Indore', 'Gwalior', 'Jabalpur', 'Raipur',
  'Kolkata', 'Siliguri', 'Durgapur', 'Patna', 'Gaya', 'Ranchi', 'Jamshedpur', 'Bhubaneswar', 'Cuttack', 'Guwahati', 'Dibrugarh', 'Agartala', 'Imphal', 'Shillong', 'Aizawl', 'Dimapur',
  'Dehradun', 'Haridwar', 'Shimla', 'Srinagar', 'Jammu', 'Leh', 'Panaji', 'Puducherry', 'Port Blair'
];

const EMPTY = {
  name: '', email: '', password: '', phone: '', city: '', businessState: '',
  businessType: 'retail', status: 'newClient', frequency: 'Daily',
  parcelVolume: 0, activeContracts: 0, provider: '', efficiency: '',
  logisticsSegment: '', transitFrom: '', transitTo: '', neighbourhood: '',
  surveyAddress: '', surveyLat: '', surveyLng: '', dataConsent: 'full', notes: '', pincode: ''
};

const formatOption = (s) => typeof s === 'string' ? s.charAt(0).toUpperCase() + s.slice(1).replace(/([A-Z])/g, ' $1').trim() : s;
const withValue = (opts, v) => (v && !opts.includes(v) ? [v, ...opts] : opts);

export default function ClientFormDialog({ open, mode, initial, onClose, onSaved }) {
  const isEdit = mode === 'edit';
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'));
  const [form, setForm] = useState(EMPTY);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [gettingLocation, setGettingLocation] = useState(false);

  const handleGPS = () => {
    if (!navigator.geolocation) {
      alert("Geolocation is not supported by your browser");
      return;
    }
    setGettingLocation(true);
    navigator.geolocation.getCurrentPosition(async (pos) => {
      const lat = pos.coords.latitude;
      const lng = pos.coords.longitude;
      setForm((f) => ({ ...f, surveyLat: lat, surveyLng: lng }));

      try {
        const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}`);
        const data = await res.json();
        if (data && data.address) {
          const address = data.address;
          const city = address.city || address.town || address.village || address.county || '';
          const state = address.state || '';
          const pincode = address.postcode || '';
          const display = data.display_name || '';
          
          setForm((f) => ({
            ...f,
            city: city || f.city,
            businessState: state || f.businessState,
            pincode: pincode || f.pincode,
            surveyAddress: display || f.surveyAddress
          }));
        }
      } catch (e) {
        console.error("Reverse geocoding failed", e);
      } finally {
        setGettingLocation(false);
      }
    }, (err) => {
      alert("Unable to retrieve your location");
      setGettingLocation(false);
    });
  };

  useEffect(() => {
    if (open) {
      setForm({ ...EMPTY, ...(initial || {}) });
      setError(null);
    }
  }, [open, initial]);

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const handleSave = async () => {
    if (!form.name.trim()) { setError('Client name is required.'); return; }
    setSaving(true);
    setError(null);

    const lat = form.surveyLat === '' ? undefined : Number(form.surveyLat);
    const lng = form.surveyLng === '' ? undefined : Number(form.surveyLng);

    const payload = {
      first_name: form.name.trim(),
      phone: form.phone,
      city: form.city,
      businessState: form.businessState,
      businessType: form.businessType,
      status: form.status,
      frequency: form.frequency,
      parcelVolume: Number(form.parcelVolume) || 0,
      activeContracts: Number(form.activeContracts) || 0,
      provider: form.provider,
      efficiency: form.efficiency,
      logisticsSegment: form.logisticsSegment,
      transitFrom: form.transitFrom,
      transitTo: form.transitTo,
      neighbourhood: form.neighbourhood,
      pincode: form.pincode,
      surveyAddress: form.surveyAddress,
      dataConsent: form.dataConsent,
      notes: form.notes,
      lastUpdated: new Date().toISOString().slice(0, 10),
      registration_source: 'web',
      ...(form.email.trim() ? { email: form.email.trim() } : {}),
      ...(lat != null ? { survey_lat: lat } : {}),
      ...(lng != null ? { survey_long: lng } : {}),
    };

    try {
      if (isEdit) {
        await updateClient(initial.id, payload);
      } else {
        await createClient({ ...payload, ...(form.password ? { password: form.password } : {}) });
      }
      onSaved();
    } catch (e) {
      setError(e.message || 'Failed to save client');
    } finally {
      setSaving(false);
    }
  };

  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 fullScreen={typeof fullScreen !== 'undefined' ? fullScreen : false}>
        <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {isEdit ? 'Edit Client' : 'Add Client'}
          <IconButton onClick={onClose} size="small" disabled={saving}><CloseIcon /></IconButton>
        </DialogTitle>
        <DialogContent dividers>
          <Typography variant="overline" color="text.secondary">Business</Typography>
        <Grid container spacing={2} sx={{ mt: 0, mb: 1 }}>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Client Name *" value={form.name} onChange={set('name')} /></Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Phone" value={form.phone} onChange={set('phone')} /></Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Email" value={form.email} onChange={set('email')} /></Grid>
          {!isEdit && (
            <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Password" type="password" value={form.password} onChange={set('password')} /></Grid>
          )}
          <Grid item xs={12} sm={6}>
            <TextField select fullWidth size="small" label="Business Type" value={form.businessType} onChange={set('businessType')}>
              {withValue(BUSINESS_TYPES, form.businessType).map((o) => <MenuItem key={o} value={o}>{formatOption(o)}</MenuItem>)}
            </TextField>
          </Grid>
          <Grid item xs={12} sm={6}>
            <TextField select fullWidth size="small" label="Status" value={form.status} onChange={set('status')}>
              {withValue(STATUSES, form.status).map((o) => <MenuItem key={o} value={o}>{formatOption(o)}</MenuItem>)}
            </TextField>
          </Grid>
          <Grid item xs={12} sm={6}>
            <TextField select fullWidth size="small" label="Order Frequency" value={form.frequency} onChange={set('frequency')}>
              {withValue(FREQUENCIES, form.frequency).map((o) => <MenuItem key={o} value={o}>{formatOption(o)}</MenuItem>)}
            </TextField>
          </Grid>
          <Grid item xs={12} sm={3}><TextField fullWidth size="small" type="number" label="Parcel Volume" value={form.parcelVolume} onChange={set('parcelVolume')} /></Grid>
          <Grid item xs={12} sm={3}><TextField fullWidth size="small" type="number" label="Active Contracts" value={form.activeContracts} onChange={set('activeContracts')} /></Grid>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              autoHighlight
              options={PROVIDERS}
              value={form.provider || null}
              onChange={(e, newValue) => setForm((f) => ({ ...f, provider: newValue || '' }))}
              renderInput={(params) => <TextField {...params} fullWidth size="small" label="Current Provider" />}
            />
          </Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Efficiency" value={form.efficiency} onChange={set('efficiency')} /></Grid>
          <Grid item xs={12}><TextField fullWidth size="small" label="Logistics Segment" value={form.logisticsSegment} onChange={set('logisticsSegment')} placeholder="First Mile, Last Mile" /></Grid>
        </Grid>

        <Divider sx={{ my: 1.5 }} />
        <Typography variant="overline" color="text.secondary">Location & Transit</Typography>
        <Grid container spacing={2} sx={{ mt: 0, mb: 1 }}>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              autoHighlight
              options={CITIES}
              value={form.city || null}
              onChange={(e, newValue) => setForm((f) => ({ ...f, city: newValue || '' }))}
              renderInput={(params) => <TextField {...params} fullWidth size="small" label="City" />}
            />
          </Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="State" value={form.businessState} onChange={set('businessState')} /></Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Pincode" value={form.pincode} onChange={set('pincode')} /></Grid>
          <Grid item xs={12} sm={6}><TextField fullWidth size="small" label="Neighbourhood / Zone" value={form.neighbourhood} onChange={set('neighbourhood')} /></Grid>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              autoHighlight
              options={CITIES}
              value={form.transitFrom || null}
              onChange={(e, newValue) => setForm((f) => ({ ...f, transitFrom: newValue || '' }))}
              renderInput={(params) => <TextField {...params} fullWidth size="small" label="Transit From" />}
            />
          </Grid>
          <Grid item xs={12} sm={6}>
            <Autocomplete
              autoHighlight
              options={CITIES}
              value={form.transitTo || null}
              onChange={(e, newValue) => setForm((f) => ({ ...f, transitTo: newValue || '' }))}
              renderInput={(params) => <TextField {...params} fullWidth size="small" label="Transit To" />}
            />
          </Grid>
          <Grid item xs={12} sm={3}><TextField fullWidth size="small" type="number" label="Latitude" value={form.surveyLat} onChange={set('surveyLat')} /></Grid>
          <Grid item xs={12} sm={3}><TextField fullWidth size="small" type="number" label="Longitude" value={form.surveyLng} onChange={set('surveyLng')} /></Grid>
          <Grid item xs={12} sm={6} display="flex" alignItems="center">
            <Button 
              variant="outlined" 
              size="small" 
              onClick={handleGPS} 
              disabled={gettingLocation} 
              startIcon={gettingLocation ? <CircularProgress size={16} /> : <MyLocationIcon />}
              fullWidth
            >
              Get GPS Location
            </Button>
          </Grid>
          <Grid item xs={12}><TextField fullWidth size="small" label="Survey Address" value={form.surveyAddress} onChange={set('surveyAddress')} multiline minRows={2} /></Grid>
        </Grid>

        <Divider sx={{ my: 1.5 }} />
        <Typography variant="overline" color="text.secondary">Other</Typography>
        <Grid container spacing={2} sx={{ mt: 0 }}>
          <Grid item xs={12} sm={6}>
            <TextField select fullWidth size="small" label="Data Consent" value={form.dataConsent} onChange={set('dataConsent')}>
              {withValue(CONSENTS, form.dataConsent).map((o) => <MenuItem key={o} value={o}>{formatOption(o)}</MenuItem>)}
            </TextField>
          </Grid>
          <Grid item xs={12}><TextField fullWidth size="small" label="Notes" value={form.notes} onChange={set('notes')} multiline minRows={2} /></Grid>
        </Grid>
      </DialogContent>
      <DialogActions sx={{ px: 3, py: 2 }}>
        <Button onClick={onClose} disabled={saving}>Cancel</Button>
        <Button variant="contained" onClick={handleSave} disabled={saving} startIcon={saving ? <CircularProgress size={16} color="inherit" /> : null}>
          {isEdit ? 'Save Changes' : 'Create Client'}
        </Button>
      </DialogActions>
    </Dialog>
    </>
  );
}
