import { useState, useEffect } from 'react';
import { MapPin } from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
import { Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
import { FormLayout } from '@astryxdesign/core/FormLayout';
import { TextInput } from '@astryxdesign/core/TextInput';
import { NumberInput } from '@astryxdesign/core/NumberInput';
import { TextArea } from '@astryxdesign/core/TextArea';
import { Selector } from '@astryxdesign/core/Selector';
import { Divider } from '@astryxdesign/core/Divider';
import { Banner } from '@astryxdesign/core/Banner';

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);
const selectorOptions = (opts, v) => withValue(opts, v).map((o) => ({ value: o, label: formatOption(o) }));

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

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

  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 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 (
    <Dialog isOpen={open} onOpenChange={(o) => { if (!o) onClose(); }} width={800} maxHeight="90dvh" purpose="form">
      <Layout
        header={<DialogHeader title={isEdit ? 'Edit Client' : 'Add Client'} onOpenChange={(o) => { if (!o) onClose(); }} />}
        content={
          <LayoutContent>
            <FormLayout>
              {error && <Banner status="error" title={error} />}

              <Divider label="Business" />
              <FormLayout direction="horizontal">
                <TextInput label="Client Name" isRequired value={form.name} onChange={set('name')} />
                <TextInput label="Phone" value={form.phone} onChange={set('phone')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <TextInput label="Email" type="email" value={form.email} onChange={set('email')} />
                {!isEdit && <TextInput label="Password" type="password" value={form.password} onChange={set('password')} />}
              </FormLayout>
              <FormLayout direction="horizontal">
                <Selector label="Business Type" options={selectorOptions(BUSINESS_TYPES, form.businessType)} value={form.businessType} onChange={set('businessType')} />
                <Selector label="Status" options={selectorOptions(STATUSES, form.status)} value={form.status} onChange={set('status')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <Selector label="Order Frequency" options={selectorOptions(FREQUENCIES, form.frequency)} value={form.frequency} onChange={set('frequency')} />
                <NumberInput label="Parcel Volume" value={Number(form.parcelVolume) || 0} onChange={set('parcelVolume')} />
                <NumberInput label="Contracts" value={Number(form.activeContracts) || 0} onChange={set('activeContracts')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <div>
                  <TextInput label="Current Provider" list="providers-list" value={form.provider || ''} onChange={set('provider')} />
                  <datalist id="providers-list">
                    {PROVIDERS.map((p) => <option key={p} value={p} />)}
                  </datalist>
                </div>
                <TextInput label="Efficiency" value={form.efficiency} onChange={set('efficiency')} />
              </FormLayout>
              <TextInput label="Logistics Segment" placeholder="First Mile, Last Mile" value={form.logisticsSegment} onChange={set('logisticsSegment')} />

              <Divider label="Location & Transit" />
              <FormLayout direction="horizontal">
                <div>
                  <TextInput label="City" list="cities-list" value={form.city || ''} onChange={set('city')} />
                  <datalist id="cities-list">
                    {CITIES.map((c) => <option key={c} value={c} />)}
                  </datalist>
                </div>
                <TextInput label="State" value={form.businessState} onChange={set('businessState')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <TextInput label="Pincode" value={form.pincode} onChange={set('pincode')} />
                <TextInput label="Neighbourhood / Zone" value={form.neighbourhood} onChange={set('neighbourhood')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <div>
                  <TextInput label="Transit From" list="cities-list-from" value={form.transitFrom || ''} onChange={set('transitFrom')} />
                  <datalist id="cities-list-from">
                    {CITIES.map((c) => <option key={c} value={c} />)}
                  </datalist>
                </div>
                <div>
                  <TextInput label="Transit To" list="cities-list-to" value={form.transitTo || ''} onChange={set('transitTo')} />
                  <datalist id="cities-list-to">
                    {CITIES.map((c) => <option key={c} value={c} />)}
                  </datalist>
                </div>
              </FormLayout>
              <FormLayout direction="horizontal">
                <NumberInput label="Latitude" value={form.surveyLat === '' ? undefined : Number(form.surveyLat)} onChange={set('surveyLat')} />
                <NumberInput label="Longitude" value={form.surveyLng === '' ? undefined : Number(form.surveyLng)} onChange={set('surveyLng')} />
                <div style={{ display: 'flex', alignItems: 'flex-end' }}>
                  <Button
                    label={gettingLocation ? "Getting GPS..." : "Get GPS Location"}
                    variant="secondary"
                    icon={gettingLocation ? undefined : <MapPin size={16} />}
                    onClick={handleGPS}
                    isDisabled={gettingLocation}
                    style={{ width: '100%', height: '40px' }}
                  />
                </div>
              </FormLayout>
              <TextArea label="Survey Address" rows={2} value={form.surveyAddress} onChange={set('surveyAddress')} />

              <Divider label="Other" />
              <Selector label="Data Consent" options={selectorOptions(CONSENTS, form.dataConsent)} value={form.dataConsent} onChange={set('dataConsent')} />
              <TextArea label="Notes" rows={2} value={form.notes} onChange={set('notes')} />
            </FormLayout>
          </LayoutContent>
        }
        footer={
          <LayoutFooter hasDivider>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
              <Button label="Cancel" variant="ghost" onClick={onClose} isDisabled={saving} />
              <Button
                label={isEdit ? 'Save Changes' : 'Create Client'}
                variant="primary"
                onClick={handleSave}
                isDisabled={saving}
                isLoading={saving}
              />
            </div>
          </LayoutFooter>
        }
      />
    </Dialog>
  );
}
