'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { ChevronDown, MapPin, Camera, Upload, Send, Loader2, CheckCircle, Wifi, User, Phone, Home, Package, Calendar, Signal, AlertCircle, X, RefreshCw, Info,  } from 'lucide-react';
import {
  technicians,
  getAssignedONTs,
  subscriptionPackages,
  generateSCId,
  formatDate,
  DispatchRecord,
} from '@/lib/mockData';
import StatusBadge from '@/components/ui/StatusBadge';

interface InstallFormValues {
  technicianId: string;
  scId: string;
  selectedONTId: string;
  ontSerialNumber: string;
  customerName: string;
  customerAddress: string;
  customerPhone: string;
  subscriptionPackage: string;
  installDate: string;
  gpsLat: string;
  gpsLng: string;
  signalAttenuation: string;
  notes: string;
}

export default function TechnicianInstallationPage() {
  const [assignedONTs, setAssignedONTs] = useState<DispatchRecord[]>([]);
  const [selectedONT, setSelectedONT] = useState<DispatchRecord | null>(null);
  const [scId, setScId] = useState('');
  const [gpsCapturing, setGpsCapturing] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [photoHouse, setPhotoHouse] = useState<string | null>(null);
  const [photoONT, setPhotoONT] = useState<string | null>(null);
  const [photoSignal, setPhotoSignal] = useState<string | null>(null);
  const [today, setToday] = useState('');

  useEffect(() => {
    const now = new Date();
    const yyyy = now.getFullYear();
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    setToday(`${yyyy}-${mm}-${dd}`);
  }, []);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm<InstallFormValues>({
    defaultValues: {
      technicianId: '',
      scId: '',
      selectedONTId: '',
      ontSerialNumber: '',
      customerName: '',
      customerAddress: '',
      customerPhone: '',
      subscriptionPackage: '',
      installDate: '',
      gpsLat: '',
      gpsLng: '',
      signalAttenuation: '',
      notes: '',
    },
  });

  const technicianId = watch('technicianId');

  useEffect(() => {
    if (technicianId) {
      // Backend integration point: GET /api/technicians/{id}/assigned-onts
      const onts = getAssignedONTs(technicianId);
      setAssignedONTs(onts);
      setSelectedONT(null);
      setValue('ontSerialNumber', '');
      setValue('selectedONTId', '');

      const newScId = generateSCId();
      setScId(newScId);
      setValue('scId', newScId);
    } else {
      setAssignedONTs([]);
      setSelectedONT(null);
    }
  }, [technicianId, setValue]);

  const handleONTSelect = useCallback(
    (ont: DispatchRecord) => {
      setSelectedONT(ont);
      setValue('ontSerialNumber', ont.serialNumber);
      setValue('selectedONTId', ont.id);
    },
    [setValue]
  );

  const handleGPSCapture = useCallback(async () => {
    setGpsCapturing(true);
    // Backend integration point: navigator.geolocation.getCurrentPosition
    await new Promise((r) => setTimeout(r, 1500));
    setValue('gpsLat', '-7.257472');
    setValue('gpsLng', '112.752088');
    setGpsCapturing(false);
    toast.success('Koordinat GPS berhasil diambil');
  }, [setValue]);

  const handlePhotoUpload = (
    e: React.ChangeEvent<HTMLInputElement>,
    setter: (v: string | null) => void
  ) => {
    const file = e.target.files?.[0];
    if (file) {
      const url = URL.createObjectURL(file);
      setter(url);
    }
  };

  const onSubmit = useCallback(
    async (data: InstallFormValues) => {
      if (!selectedONT) {
        toast.error('Pilih unit ONT terlebih dahulu');
        return;
      }
      setSubmitting(true);
      // Backend integration point: POST /api/installations with form data + photos
      await new Promise((r) => setTimeout(r, 2000));
      setSubmitting(false);
      setSubmitted(true);
      toast.success(`Form pemasangan ${data.scId} berhasil dikirim ke Telegram`);
    },
    [selectedONT]
  );

  const handleReset = () => {
    reset();
    setSelectedONT(null);
    setAssignedONTs([]);
    setScId('');
    setPhotoHouse(null);
    setPhotoONT(null);
    setPhotoSignal(null);
    setSubmitted(false);
  };

  const selectedTech = technicians.find((t) => t.id === technicianId);

  if (submitted) {
    return (
      <div className="flex flex-col h-full">
        <div className="px-6 py-5 border-b border-border bg-card">
          <h1 className="text-xl font-bold text-foreground">Form Pemasangan Pelanggan</h1>
        </div>
        <div className="flex-1 flex items-center justify-center px-6 py-12">
          <div className="card-elevated p-10 text-center max-w-md w-full">
            <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
              <CheckCircle size={32} className="text-accent" />
            </div>
            <h2 className="text-xl font-bold text-foreground mb-2">Berhasil Dikirim!</h2>
            <p className="text-muted-foreground mb-1">
              Dokumen pemasangan <span className="font-mono font-bold text-foreground">{scId}</span>
            </p>
            <p className="text-sm text-muted-foreground mb-6">
              telah dikirim ke grup Telegram teknisi dan disimpan ke sistem.
            </p>
            <div className="bg-green-50 border border-green-200 rounded-lg px-4 py-3 mb-6 text-left space-y-1">
              <p className="text-xs text-muted-foreground">SN ONT yang dipasang:</p>
              <p className="font-mono font-bold text-sm text-foreground">{selectedONT?.serialNumber}</p>
              <p className="text-xs text-muted-foreground">{selectedONT?.deviceBrand} {selectedONT?.deviceModel}</p>
            </div>
            <button onClick={handleReset} className="btn-primary w-full justify-center">
              <RefreshCw size={15} />
              Form Pemasangan Baru
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="px-6 py-5 border-b border-border bg-card">
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div>
            <h1 className="text-xl font-bold text-foreground">Form Pemasangan Pelanggan</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              Generator dokumen pemasangan ONT untuk pelanggan baru
            </p>
          </div>
          {scId && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg px-3 py-2">
              <p className="text-xs text-muted-foreground">SC ID</p>
              <p className="font-mono font-bold text-sm text-primary">{scId}</p>
            </div>
          )}
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="flex-1 overflow-y-auto">
        <div className="max-w-screen-2xl mx-auto px-6 py-5 space-y-5">

          {/* Step 1: Select Technician */}
          <div className="card-elevated">
            <div className="px-5 py-4 border-b border-border flex items-center gap-3">
              <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0">
                <span className="text-xs font-bold text-primary-foreground">1</span>
              </div>
              <div>
                <h2 className="text-base font-semibold text-foreground">Pilih Teknisi</h2>
                <p className="text-xs text-muted-foreground">Pilih nama teknisi untuk melihat ONT yang di-assign</p>
              </div>
            </div>
            <div className="px-5 py-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Nama Teknisi <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <select
                      {...register('technicianId', { required: 'Pilih nama teknisi' })}
                      className="input-base appearance-none pr-8"
                    >
                      <option value="">-- Pilih Nama Teknisi --</option>
                      {technicians.map((t) => (
                        <option key={`form-tech-${t.id}`} value={t.id}>
                          {t.name} — {t.pop}
                        </option>
                      ))}
                    </select>
                    <ChevronDown size={15} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                  </div>
                  {errors.technicianId && (
                    <p className="text-xs text-destructive mt-1">{errors.technicianId.message}</p>
                  )}
                </div>

                {selectedTech && (
                  <div className="bg-blue-50 border border-blue-200 rounded-lg px-4 py-3 flex items-start gap-3">
                    <div className="w-9 h-9 rounded-full bg-primary flex items-center justify-center shrink-0">
                      <span className="text-sm font-bold text-primary-foreground">{selectedTech.avatarInitials}</span>
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-foreground">{selectedTech.name}</p>
                      <p className="text-xs text-muted-foreground">{selectedTech.pop} · {selectedTech.role}</p>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        <span className="text-primary font-medium">{assignedONTs.length} ONT</span> tersedia untuk dipilih
                      </p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Step 2: Select ONT */}
          {technicianId && (
            <div className="card-elevated slide-up">
              <div className="px-5 py-4 border-b border-border flex items-center gap-3">
                <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0">
                  <span className="text-xs font-bold text-primary-foreground">2</span>
                </div>
                <div className="flex-1">
                  <h2 className="text-base font-semibold text-foreground">Pilih Unit ONT</h2>
                  <p className="text-xs text-muted-foreground">Unit yang sudah di-assign dari gudang ke teknisi ini</p>
                </div>
                {selectedONT && (
                  <StatusBadge variant="assigned" customLabel="ONT Dipilih ✓" />
                )}
              </div>
              <div className="px-5 py-4">
                {assignedONTs.length === 0 ? (
                  <div className="flex flex-col items-center gap-2 py-8">
                    <div className="w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center">
                      <AlertCircle size={22} className="text-warning" />
                    </div>
                    <p className="text-sm font-medium text-foreground">Tidak ada ONT yang di-assign</p>
                    <p className="text-xs text-muted-foreground text-center max-w-xs">
                      Teknisi ini belum menerima unit ONT dari gudang. Hubungi admin gudang untuk dispatch unit terlebih dahulu.
                    </p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
                    {assignedONTs.map((ont) => (
                      <button
                        key={`ont-card-${ont.id}`}
                        type="button"
                        onClick={() => handleONTSelect(ont)}
                        className={`text-left p-4 rounded-lg border-2 transition-all duration-150 ${
                          selectedONT?.id === ont.id
                            ? 'ont-card-selected' :'border-border hover:ont-card-hover bg-card'
                        }`}
                      >
                        <div className="flex items-start justify-between mb-2">
                          <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center">
                            <Wifi size={16} className="text-primary" />
                          </div>
                          {selectedONT?.id === ont.id && (
                            <CheckCircle size={16} className="text-primary" />
                          )}
                        </div>
                        <p className="font-mono text-xs font-bold text-foreground leading-tight break-all">
                          {ont.serialNumber}
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">
                          {ont.deviceBrand} {ont.deviceModel}
                        </p>
                        <p className="text-xs text-muted-foreground mt-0.5">
                          Dispatch: {formatDate(ont.dispatchDate!).split(' ')[0]}
                        </p>
                      </button>
                    ))}
                  </div>
                )}

                {selectedONT && (
                  <div className="mt-3 pt-3 border-t border-border">
                    <div className="flex items-center gap-2">
                      <CheckCircle size={14} className="text-accent" />
                      <p className="text-sm text-foreground">
                        SN ONT terpilih:{' '}
                        <span className="font-mono font-bold">{selectedONT.serialNumber}</span>
                        <span className="text-muted-foreground ml-2">
                          ({selectedONT.deviceBrand} {selectedONT.deviceModel})
                        </span>
                      </p>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Step 3: Customer Data */}
          {selectedONT && (
            <div className="card-elevated slide-up">
              <div className="px-5 py-4 border-b border-border flex items-center gap-3">
                <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0">
                  <span className="text-xs font-bold text-primary-foreground">3</span>
                </div>
                <div>
                  <h2 className="text-base font-semibold text-foreground">Data Pelanggan</h2>
                  <p className="text-xs text-muted-foreground">Informasi pelanggan yang akan dipasang</p>
                </div>
              </div>

              <div className="px-5 py-4 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                {/* SC ID */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">SC ID</label>
                  <p className="text-xs text-muted-foreground mb-1">Auto-generated, tidak dapat diubah</p>
                  <input
                    {...register('scId')}
                    readOnly
                    className="input-base bg-muted font-mono text-sm cursor-not-allowed"
                  />
                </div>

                {/* Customer Name */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Nama Pelanggan <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <User size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                    <input
                      {...register('customerName', { required: 'Nama pelanggan wajib diisi' })}
                      placeholder="Nama lengkap pelanggan"
                      className="input-base pl-8"
                    />
                  </div>
                  {errors.customerName && (
                    <p className="text-xs text-destructive mt-1">{errors.customerName.message}</p>
                  )}
                </div>

                {/* Phone */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Nomor Telepon <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <Phone size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                    <input
                      {...register('customerPhone', {
                        required: 'Nomor telepon wajib diisi',
                        pattern: { value: /^[0-9+]{10,15}$/, message: 'Format nomor tidak valid' },
                      })}
                      placeholder="08xxxxxxxxxx"
                      type="tel"
                      className="input-base pl-8"
                    />
                  </div>
                  {errors.customerPhone && (
                    <p className="text-xs text-destructive mt-1">{errors.customerPhone.message}</p>
                  )}
                </div>

                {/* Address */}
                <div className="md:col-span-2 xl:col-span-3">
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Alamat Pemasangan <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <Home size={14} className="absolute left-2.5 top-3 text-muted-foreground" />
                    <textarea
                      {...register('customerAddress', { required: 'Alamat wajib diisi' })}
                      placeholder="Alamat lengkap termasuk RT/RW, kelurahan, kecamatan"
                      rows={2}
                      className="input-base pl-8 resize-none"
                    />
                  </div>
                  {errors.customerAddress && (
                    <p className="text-xs text-destructive mt-1">{errors.customerAddress.message}</p>
                  )}
                </div>

                {/* Package */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Paket Berlangganan <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <select
                      {...register('subscriptionPackage', { required: 'Pilih paket berlangganan' })}
                      className="input-base appearance-none pr-8"
                    >
                      <option value="">-- Pilih Paket --</option>
                      {subscriptionPackages.map((pkg) => (
                        <option key={`pkg-${pkg}`} value={pkg}>{pkg}</option>
                      ))}
                    </select>
                    <ChevronDown size={15} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                  </div>
                  {errors.subscriptionPackage && (
                    <p className="text-xs text-destructive mt-1">{errors.subscriptionPackage.message}</p>
                  )}
                </div>

                {/* Install Date */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Tanggal Pemasangan <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <Calendar size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                    <input
                      {...register('installDate', { required: 'Tanggal pemasangan wajib diisi' })}
                      type="date"
                      defaultValue={today}
                      className="input-base pl-8"
                    />
                  </div>
                  {errors.installDate && (
                    <p className="text-xs text-destructive mt-1">{errors.installDate.message}</p>
                  )}
                </div>

                {/* Signal attenuation */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Redaman Sinyal (dBm)
                  </label>
                  <p className="text-xs text-muted-foreground mb-1">Nilai redaman dari OPM/power meter</p>
                  <div className="relative">
                    <Signal size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                    <input
                      {...register('signalAttenuation')}
                      placeholder="-20.5"
                      type="text"
                      className="input-base pl-8 font-mono"
                    />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 4: GPS + Photos */}
          {selectedONT && (
            <div className="card-elevated slide-up">
              <div className="px-5 py-4 border-b border-border flex items-center gap-3">
                <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0">
                  <span className="text-xs font-bold text-primary-foreground">4</span>
                </div>
                <div>
                  <h2 className="text-base font-semibold text-foreground">Lokasi & Dokumentasi Foto</h2>
                  <p className="text-xs text-muted-foreground">GPS koordinat dan foto dokumentasi lapangan</p>
                </div>
              </div>

              <div className="px-5 py-4 space-y-5">
                {/* GPS */}
                <div>
                  <p className="text-sm font-medium text-foreground mb-2 flex items-center gap-1.5">
                    <MapPin size={15} className="text-primary" />
                    Koordinat GPS
                  </p>
                  <div className="flex flex-wrap items-end gap-3">
                    <div className="flex-1 min-w-[140px]">
                      <label className="block text-xs text-muted-foreground mb-1">Latitude</label>
                      <input
                        {...register('gpsLat')}
                        placeholder="-7.257472"
                        readOnly
                        className="input-base font-mono text-sm bg-muted"
                      />
                    </div>
                    <div className="flex-1 min-w-[140px]">
                      <label className="block text-xs text-muted-foreground mb-1">Longitude</label>
                      <input
                        {...register('gpsLng')}
                        placeholder="112.752088"
                        readOnly
                        className="input-base font-mono text-sm bg-muted"
                      />
                    </div>
                    <button
                      type="button"
                      onClick={handleGPSCapture}
                      disabled={gpsCapturing}
                      className="btn-secondary flex items-center gap-2 whitespace-nowrap"
                    >
                      {gpsCapturing ? (
                        <><Loader2 size={14} className="animate-spin" />Mengambil GPS...</>
                      ) : (
                        <><MapPin size={14} />Ambil GPS</>
                      )}
                    </button>
                  </div>
                </div>

                {/* Photos */}
                <div>
                  <p className="text-sm font-medium text-foreground mb-3 flex items-center gap-1.5">
                    <Camera size={15} className="text-primary" />
                    Foto Dokumentasi
                  </p>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <PhotoUploadZone
                      label="Foto Rumah Pelanggan"
                      hint="Tampak depan rumah pelanggan"
                      preview={photoHouse}
                      onChange={(e) => handlePhotoUpload(e, setPhotoHouse)}
                      onClear={() => setPhotoHouse(null)}
                      id="photo-house"
                    />
                    <PhotoUploadZone
                      label="Foto SN ONT"
                      hint="Label serial number pada unit ONT"
                      preview={photoONT}
                      onChange={(e) => handlePhotoUpload(e, setPhotoONT)}
                      onClear={() => setPhotoONT(null)}
                      id="photo-ont"
                    />
                    <PhotoUploadZone
                      label="Foto Redaman Sinyal"
                      hint="Layar OPM / power meter"
                      preview={photoSignal}
                      onChange={(e) => handlePhotoUpload(e, setPhotoSignal)}
                      onClear={() => setPhotoSignal(null)}
                      id="photo-signal"
                    />
                  </div>
                </div>

                {/* Notes */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Catatan Pemasangan
                  </label>
                  <textarea
                    {...register('notes')}
                    rows={2}
                    placeholder="Catatan teknis, kendala, atau informasi tambahan..."
                    className="input-base resize-none"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Submit bar */}
          {selectedONT && (
            <div className="card-elevated px-5 py-4 flex flex-wrap items-center justify-between gap-4 bg-slate-50 border-primary/20 slide-up">
              <div className="flex items-start gap-3">
                <Info size={16} className="text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-medium text-foreground">Siap kirim ke Telegram?</p>
                  <p className="text-xs text-muted-foreground">
                    Dokumen akan dikirim ke grup Telegram teknisi dan disimpan ke sistem backend
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <button type="button" onClick={handleReset} className="btn-secondary">
                  Reset Form
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="btn-primary"
                >
                  {submitting ? (
                    <><Loader2 size={15} className="animate-spin" />Mengirim...</>
                  ) : (
                    <><Send size={15} />Kirim ke Telegram</>
                  )}
                </button>
              </div>
            </div>
          )}
        </div>
      </form>
    </div>
  );
}

function PhotoUploadZone({
  label,
  hint,
  preview,
  onChange,
  onClear,
  id,
}: {
  label: string;
  hint: string;
  preview: string | null;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onClear: () => void;
  id: string;
}) {
  return (
    <div className="space-y-1">
      <p className="text-xs font-medium text-foreground">{label}</p>
      <p className="text-xs text-muted-foreground">{hint}</p>
      <div className="relative">
        {preview ? (
          <div className="relative rounded-lg overflow-hidden border-2 border-accent h-36">
            <img src={preview} alt={label} className="w-full h-full object-cover" />
            <button
              type="button"
              onClick={onClear}
              className="absolute top-2 right-2 w-6 h-6 rounded-full bg-black/60 flex items-center justify-center hover:bg-black/80 transition-colors"
            >
              <X size={12} className="text-white" />
            </button>
            <div className="absolute bottom-2 left-2">
              <span className="text-xs bg-accent text-white px-2 py-0.5 rounded font-medium flex items-center gap-1">
                <CheckCircle size={10} />
                Foto ditambahkan
              </span>
            </div>
          </div>
        ) : (
          <label
            htmlFor={id}
            className="flex flex-col items-center justify-center h-36 rounded-lg border-2 border-dashed border-border bg-muted/40 hover:bg-muted cursor-pointer transition-colors"
          >
            <Upload size={20} className="text-muted-foreground mb-2" />
            <p className="text-xs text-muted-foreground text-center px-2">
              Klik untuk upload atau ambil foto
            </p>
          </label>
        )}
        <input
          id={id}
          type="file"
          accept="image/*"
          capture="environment"
          onChange={onChange}
          className="sr-only"
        />
      </div>
    </div>
  );
}