'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { createMember, checkDuplicateMember } from '@/lib/actions/members';
import { getCountries, getStates, getCities, getAreas, getCenters } from '@/lib/actions/geography';
import { getUsers } from '@/lib/actions/users';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';

export default function AddMemberPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Selector reference lists
  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const [areas, setAreas] = useState<any[]>([]);
  const [centers, setCenters] = useState<any[]>([]);
  const [incharges, setIncharges] = useState<any[]>([]);

  // Duplicate warning state
  const [duplicates, setDuplicates] = useState<any[]>([]);
  const [duplicateCheckedNum, setDuplicateCheckedNum] = useState('');

  // Form state
  const [form, setForm] = useState({
    name: '',
    gender: 'Male',
    mobile: '',
    altMobile: '',
    email: '',
    address: '',
    countryId: '',
    stateId: '',
    cityId: '',
    areaId: '',
    assignedCenterId: '',
    assignedInchargeId: '',
    status: 'Visitor' as 'Visitor' | 'Regular Attendee' | 'Member' | 'Inactive',
    joiningDate: new Date().toISOString().substring(0, 10),
    internalNotes: ''
  });

  useEffect(() => {
    loadCountries();
    loadIncharges();
  }, []);

  const loadCountries = async () => {
    const list = await getCountries();
    setCountries(list);
    if (list.length > 0) {
      setForm(f => ({ ...f, countryId: list[0]._id }));
      loadStates(list[0]._id);
    }
  };

  const loadIncharges = async () => {
    try {
      const list = await getUsers();
      setIncharges(list.filter((u: any) => u.role === 'AREA_INCHARGE' || u.role === 'CITY_HEAD'));
    } catch {
      // Bypassed if view users is restricted to Super Admin
    }
  };

  const loadStates = async (cId: string) => {
    setStates([]);
    setCities([]);
    setAreas([]);
    setCenters([]);
    if (!cId) return;
    const list = await getStates(cId);
    setStates(list);
    if (list.length > 0) {
      setForm(f => ({ ...f, stateId: list[0]._id }));
      loadCities(list[0]._id);
    }
  };

  const loadCities = async (sId: string) => {
    setCities([]);
    setAreas([]);
    setCenters([]);
    if (!sId) return;
    const list = await getCities(sId);
    setCities(list);
    if (list.length > 0) {
      setForm(f => ({ ...f, cityId: list[0]._id }));
      loadAreas(list[0]._id);
    }
  };

  const loadAreas = async (cityId: string) => {
    setAreas([]);
    setCenters([]);
    if (!cityId) return;
    const list = await getAreas(cityId);
    setAreas(list);
    if (list.length > 0) {
      setForm(f => ({ ...f, areaId: list[0]._id }));
      loadCenters(list[0]._id);
    }
  };

  const loadCenters = async (areaId: string) => {
    setCenters([]);
    if (!areaId) return;
    const list = await getCenters(areaId);
    setCenters(list);
    if (list.length > 0) {
      setForm(f => ({ ...f, assignedCenterId: list[0]._id }));
    }
  };

  // Trigger duplicate mobile checking
  const checkDuplicates = async () => {
    if (!form.mobile || form.mobile === duplicateCheckedNum) return;
    try {
      const dup = await checkDuplicateMember(form.name, form.mobile, form.cityId);
      if (dup.isDuplicate) {
        setDuplicates(dup.matches);
      } else {
        setDuplicates([]);
      }
      setDuplicateCheckedNum(form.mobile);
    } catch (err) {
      console.error(err);
    }
  };

  const handleNext = () => {
    if (step === 1 && !form.name) {
      alert('Please fill out Name');
      return;
    }
    if (step === 2 && (!form.countryId || !form.stateId || !form.cityId || !form.areaId)) {
      alert('Please configure all geographic references');
      return;
    }
    setStep(step + 1);
  };

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

    try {
      const result = await createMember(form);
      if (result.success) {
        router.push(`/members/${result.data._id}`);
        router.refresh();
      }
    } catch (err: any) {
      setError(err.message);
      setIsLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl md:text-3xl font-bold text-gray-900 font-sans">Register Member</h1>
        <p className="mt-1 text-sm text-gray-500">Progressive member onboarding registration details.</p>
      </div>

      {/* Steps Indicator Progress bar */}
      <div className="flex items-center gap-2">
        <span className={`h-2.5 flex-1 rounded-full ${step >= 1 ? 'bg-brand-primary' : 'bg-gray-200'}`}></span>
        <span className={`h-2.5 flex-1 rounded-full ${step >= 2 ? 'bg-brand-primary' : 'bg-gray-200'}`}></span>
        <span className={`h-2.5 flex-1 rounded-full ${step >= 3 ? 'bg-brand-primary' : 'bg-gray-200'}`}></span>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-800 p-4 rounded-xl text-sm font-semibold">
          {error}
        </div>
      )}

      <Card className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* STEP 1: BASIC INFORMATION */}
          {step === 1 && (
            <div className="space-y-4">
              <h3 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-2 mb-4">Basic Information</h3>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Full Name</label>
                <Input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Gender</label>
                  <select
                    value={form.gender}
                    onChange={(e) => setForm({ ...form, gender: e.target.value })}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                  >
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Other">Other</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Primary Mobile</label>
                  <Input
                    type="tel"
                    value={form.mobile}
                    onChange={(e) => setForm({ ...form, mobile: e.target.value })}
                    onBlur={checkDuplicates}
                  />
                </div>
              </div>

              {/* Duplicate Mobile Warning */}
              {duplicates.length > 0 && (
                <div className="rounded-xl bg-orange-50 p-4 border border-orange-200 space-y-2 animate-pulse">
                  <div className="flex gap-2">
                    <svg className="h-5 w-5 text-orange-600" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                    </svg>
                    <span className="text-sm font-bold text-orange-800">Possible existing member(s) found:</span>
                  </div>
                  <div className="divide-y divide-orange-100 pl-7 text-xs text-orange-700 space-y-1.5">
                    {duplicates.map((dup) => (
                      <div key={dup._id} className="pt-1.5 first:pt-0">
                        {dup.name} ({dup.memberUuid}) - Location: {dup.city} / {dup.area}. Mobile is shared.
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Alternate Mobile</label>
                  <Input value={form.altMobile} onChange={(e) => setForm({ ...form, altMobile: e.target.value })} />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Email Address</label>
                  <Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                </div>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Residential Address</label>
                <Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
              </div>
            </div>
          )}

          {/* STEP 2: LOCATION INFORMATION */}
          {step === 2 && (
            <div className="space-y-4">
              <h3 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-2 mb-4">Location References</h3>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Country</label>
                  <select
                    value={form.countryId}
                    onChange={(e) => { setForm({ ...form, countryId: e.target.value }); loadStates(e.target.value); }}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                  >
                    <option value="">Select Country</option>
                    {countries.map(c => <option key={c._id} value={c._id}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">State</label>
                  <select
                    value={form.stateId}
                    onChange={(e) => { setForm({ ...form, stateId: e.target.value }); loadCities(e.target.value); }}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                    disabled={!form.countryId}
                  >
                    <option value="">Select State</option>
                    {states.map(s => <option key={s._id} value={s._id}>{s.name}</option>)}
                  </select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">City</label>
                  <select
                    value={form.cityId}
                    onChange={(e) => { setForm({ ...form, cityId: e.target.value }); loadAreas(e.target.value); }}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                    disabled={!form.stateId}
                  >
                    <option value="">Select City</option>
                    {cities.map(c => <option key={c._id} value={c._id}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Area</label>
                  <select
                    value={form.areaId}
                    onChange={(e) => { setForm({ ...form, areaId: e.target.value }); loadCenters(e.target.value); }}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                    disabled={!form.cityId}
                  >
                    <option value="">Select Area</option>
                    {areas.map(a => <option key={a._id} value={a._id}>{a.name}</option>)}
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Satsang Center</label>
                <select
                  value={form.assignedCenterId}
                  onChange={(e) => setForm({ ...form, assignedCenterId: e.target.value })}
                  className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                  disabled={!form.areaId}
                >
                  <option value="">Select Center</option>
                  {centers.map(ce => <option key={ce._id} value={ce._id}>{ce.name}</option>)}
                </select>
              </div>
            </div>
          )}

          {/* STEP 3: SATSANG OPTIONS & DETAILS */}
          {step === 3 && (
            <div className="space-y-4">
              <h3 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-2 mb-4">Satsang Membership Configurations</h3>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Membership Status</label>
                  <select
                    value={form.status}
                    onChange={(e) => setForm({ ...form, status: e.target.value as any })}
                    className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                  >
                    <option value="Visitor">Visitor</option>
                    <option value="Regular Attendee">Regular Attendee</option>
                    <option value="Member">Member</option>
                    <option value="Inactive">Inactive</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Joining Date</label>
                  <Input type="date" value={form.joiningDate} onChange={(e) => setForm({ ...form, joiningDate: e.target.value })} />
                </div>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Assigned Area Incharge</label>
                <select
                  value={form.assignedInchargeId}
                  onChange={(e) => setForm({ ...form, assignedInchargeId: e.target.value })}
                  className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
                >
                  <option value="">Select Incharge</option>
                  {incharges.map(inc => <option key={inc._id} value={inc._id}>{inc.email}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-1">Authorized Internal Notes</label>
                <Input value={form.internalNotes} onChange={(e) => setForm({ ...form, internalNotes: e.target.value })} />
                <p className="mt-1 text-xs text-gray-400">
                  Notes are secure and redacted from standard reports or public views.
                </p>
              </div>
            </div>
          )}

          {/* Controls button layout */}
          <div className="flex justify-between pt-4 border-t border-gray-150">
            {step > 1 ? (
              <Button type="button" variant="secondary" onClick={() => setStep(step - 1)}>
                Back
              </Button>
            ) : (
              <Button type="button" variant="secondary" onClick={() => router.push('/members')}>
                Cancel
              </Button>
            )}

            {step < 3 ? (
              <Button type="button" onClick={handleNext} className="bg-brand-primary text-white">
                Next Step
              </Button>
            ) : (
              <Button type="submit" isLoading={isLoading} className="bg-brand-primary text-white">
                Register Member
              </Button>
            )}
          </div>
        </form>
      </Card>
    </div>
  );
}
