import React, { useState, useRef, useEffect } from 'react';
import { ProfilPerusahaan } from '../../types/accounting';
import { Camera, Upload, Cloud, Check, X, Building, AlertCircle, Globe, ExternalLink } from 'lucide-react';

interface ProfilModalProps {
  isOpen: boolean;
  onClose: () => void;
  profile: ProfilPerusahaan;
  onSave: (updated: ProfilPerusahaan) => void;
}

export const ProfilPerusahaanModal: React.FC<ProfilModalProps> = ({
  isOpen,
  onClose,
  profile,
  onSave,
}) => {
  const [formData, setFormData] = useState<ProfilPerusahaan>(profile);
  const [logoTab, setLogoTab] = useState<'camera' | 'local' | 'cloud'>('local');
  const [cameraActive, setCameraActive] = useState(false);
  const [cameraError, setCameraError] = useState<string | null>(null);

  const videoRef = useRef<HTMLVideoElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setFormData(profile);
  }, [profile, isOpen]);

  // Handle webcam
  useEffect(() => {
    if (cameraActive && logoTab === 'camera') {
      startCamera();
    } else {
      stopCamera();
    }
    return () => {
      stopCamera();
    };
  }, [cameraActive, logoTab]);

  const startCamera = async () => {
    setCameraError(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: { ideal: 640 }, height: { ideal: 640 }, facingMode: 'user' },
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        videoRef.current.play();
      }
    } catch (err: unknown) {
      console.error('Camera error:', err);
      setCameraError('Gagal mengakses kamera. Pastikan izin kamera telah diberikan di browser.');
      setCameraActive(false);
    }
  };

  const stopCamera = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((track) => track.stop());
      streamRef.current = null;
    }
  };

  const capturePhoto = () => {
    if (videoRef.current) {
      const canvas = document.createElement('canvas');
      canvas.width = 300;
      canvas.height = 300;
      const ctx = canvas.getContext('2d');
      if (ctx) {
        ctx.drawImage(videoRef.current, 0, 0, 300, 300);
        const dataUrl = canvas.toDataURL('image/png');
        setFormData({ ...formData, logoUrl: dataUrl, logoSource: 'camera' });
        stopCamera();
        setCameraActive(false);
      }
    }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          setFormData({
            ...formData,
            logoUrl: event.target.result as string,
            logoSource: 'local',
          });
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave(formData);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4 backdrop-blur-xs">
      <div className="flex max-h-[90vh] w-full max-w-3xl flex-col rounded-lg bg-white shadow-2xl">
        {/* AdminLTE Card Header */}
        <div className="flex items-center justify-between border-b border-slate-200 bg-slate-800 px-6 py-4 text-white rounded-t-lg">
          <div className="flex items-center gap-2">
            <Building className="h-5 w-5 text-blue-400" />
            <h3 className="text-base font-semibold">Profil Instansi & Perusahaan PT Tio Mandiri Jaya</h3>
          </div>
          <button
            onClick={() => {
              stopCamera();
              onClose();
            }}
            className="text-slate-400 hover:text-white"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-6 space-y-6">
          {/* Logo Section */}
          <div className="rounded-lg border border-slate-200 bg-slate-50 p-4">
            <label className="mb-2 block text-xs font-bold uppercase tracking-wider text-slate-700">
              Logo Perusahaan (Kamera / File Lokal / Cloud Link)
            </label>

            <div className="flex flex-col sm:flex-row gap-6 items-center">
              <div className="relative flex flex-col items-center">
                <div className="h-28 w-28 overflow-hidden rounded-lg border-2 border-dashed border-blue-400 bg-white p-1 shadow-xs flex items-center justify-center">
                  {formData.logoUrl ? (
                    <img
                      src={formData.logoUrl}
                      alt="Logo Preview"
                      className="h-full w-full object-contain rounded"
                    />
                  ) : (
                    <Building className="h-10 w-10 text-slate-300" />
                  )}
                </div>
                <span className="mt-1 text-[11px] text-slate-500 font-medium capitalize">
                  Sumber: {formData.logoSource}
                </span>
              </div>

              {/* Tabs for logo source */}
              <div className="flex-1 w-full">
                <div className="flex border-b border-slate-200 mb-3 gap-2">
                  <button
                    type="button"
                    onClick={() => {
                      setLogoTab('local');
                      stopCamera();
                    }}
                    className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-t ${
                      logoTab === 'local'
                        ? 'border-b-2 border-blue-600 bg-blue-50 text-blue-700'
                        : 'text-slate-600 hover:bg-slate-100'
                    }`}
                  >
                    <Upload className="h-3.5 w-3.5" />
                    Lokal Drive
                  </button>

                  <button
                    type="button"
                    onClick={() => setLogoTab('camera')}
                    className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-t ${
                      logoTab === 'camera'
                        ? 'border-b-2 border-blue-600 bg-blue-50 text-blue-700'
                        : 'text-slate-600 hover:bg-slate-100'
                    }`}
                  >
                    <Camera className="h-3.5 w-3.5" />
                    Kamera Langsung
                  </button>

                  <button
                    type="button"
                    onClick={() => {
                      setLogoTab('cloud');
                      stopCamera();
                    }}
                    className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-t ${
                      logoTab === 'cloud'
                        ? 'border-b-2 border-blue-600 bg-blue-50 text-blue-700'
                        : 'text-slate-600 hover:bg-slate-100'
                    }`}
                  >
                    <Cloud className="h-3.5 w-3.5" />
                    Cloud / URL Drive
                  </button>
                </div>

                {/* Local Tab */}
                {logoTab === 'local' && (
                  <div className="space-y-2">
                    <p className="text-xs text-slate-600">Pilih file logo dari komputer/perangkat lokal (.png, .jpg, .svg)</p>
                    <input
                      type="file"
                      ref={fileInputRef}
                      onChange={handleFileUpload}
                      accept="image/*"
                      className="text-xs text-slate-600 file:mr-3 file:rounded file:border-0 file:bg-blue-600 file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-white hover:file:bg-blue-700"
                    />
                  </div>
                )}

                {/* Camera Tab */}
                {logoTab === 'camera' && (
                  <div className="space-y-3">
                    {cameraError && (
                      <div className="flex items-center gap-2 rounded bg-red-50 p-2 text-xs text-red-700">
                        <AlertCircle className="h-4 w-4 shrink-0" />
                        <span>{cameraError}</span>
                      </div>
                    )}

                    {!cameraActive ? (
                      <button
                        type="button"
                        onClick={() => {
                          setCameraActive(true);
                        }}
                        className="inline-flex items-center gap-1.5 rounded bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700"
                      >
                        <Camera className="h-4 w-4" />
                        Buka Kamera Webcam
                      </button>
                    ) : (
                      <div className="space-y-2">
                        <div className="relative h-44 w-44 overflow-hidden rounded border border-slate-300 bg-black">
                          <video ref={videoRef} className="h-full w-full object-cover" autoPlay playsInline />
                        </div>
                        <div className="flex gap-2">
                          <button
                            type="button"
                            onClick={capturePhoto}
                            className="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-blue-700"
                          >
                            <Check className="h-3.5 w-3.5" />
                            Ambil Gambar
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              stopCamera();
                              setCameraActive(false);
                            }}
                            className="rounded bg-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-300"
                          >
                            Batal
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Cloud Tab */}
                {logoTab === 'cloud' && (
                  <div className="space-y-2">
                    <p className="text-xs text-slate-600">
                      Masukkan URL Logo dari Google Drive publik, Cloudinary, AWS S3, atau server cloud:
                    </p>
                    <div className="flex gap-2">
                      <input
                        type="url"
                        value={formData.logoUrl}
                        onChange={(e) =>
                          setFormData({ ...formData, logoUrl: e.target.value, logoSource: 'cloud' })
                        }
                        placeholder="https://..."
                        className="flex-1 rounded border border-slate-300 px-3 py-1.5 text-xs focus:border-blue-500 focus:outline-hidden"
                      />
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Company Details Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-slate-700">Nama Perusahaan / Instansi</label>
              <input
                type="text"
                required
                value={formData.namaPerusahaan}
                onChange={(e) => setFormData({ ...formData, namaPerusahaan: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Badan Hukum</label>
              <input
                type="text"
                value={formData.badanHukum}
                onChange={(e) => setFormData({ ...formData, badanHukum: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Nomor Pokok Wajib Pajak (NPWP)</label>
              <input
                type="text"
                value={formData.npwp}
                onChange={(e) => setFormData({ ...formData, npwp: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-mono focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Nomor Induk Berusaha (NIB)</label>
              <input
                type="text"
                value={formData.nib}
                onChange={(e) => setFormData({ ...formData, nib: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-mono focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div className="sm:col-span-2">
              <label className="block text-xs font-semibold text-slate-700">Alamat Lengkap Kantor</label>
              <textarea
                rows={2}
                value={formData.alamat}
                onChange={(e) => setFormData({ ...formData, alamat: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Kota & Provinsi</label>
              <div className="grid grid-cols-2 gap-2 mt-1">
                <input
                  type="text"
                  placeholder="Kota"
                  value={formData.kota}
                  onChange={(e) => setFormData({ ...formData, kota: e.target.value })}
                  className="rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
                />
                <input
                  type="text"
                  placeholder="Provinsi"
                  value={formData.provinsi}
                  onChange={(e) => setFormData({ ...formData, provinsi: e.target.value })}
                  className="rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Telepon & Email</label>
              <div className="grid grid-cols-2 gap-2 mt-1">
                <input
                  type="text"
                  placeholder="No. Telp"
                  value={formData.telepon}
                  onChange={(e) => setFormData({ ...formData, telepon: e.target.value })}
                  className="rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
                />
                <input
                  type="email"
                  placeholder="Email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  className="rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Nama Direktur Utama (Penandatangan)</label>
              <input
                type="text"
                value={formData.namaDirektur}
                onChange={(e) => setFormData({ ...formData, namaDirektur: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Nama Kepala Akuntansi / Akuntan</label>
              <input
                type="text"
                value={formData.namaAkuntan}
                onChange={(e) => setFormData({ ...formData, namaAkuntan: e.target.value })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Website Resmi Perusahaan (Portal Web)</label>
              <div className="flex gap-2 mt-1">
                <div className="relative flex-1">
                  <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2.5 text-slate-400">
                    <Globe className="h-3.5 w-3.5" />
                  </div>
                  <input
                    type="url"
                    placeholder="https://tiomandirijaya.co.id"
                    value={formData.website}
                    onChange={(e) => setFormData({ ...formData, website: e.target.value })}
                    className="w-full rounded border border-slate-300 pl-8 pr-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
                  />
                </div>
                {formData.website && (
                  <a
                    href={formData.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 rounded bg-blue-50 border border-blue-200 px-2.5 py-2 text-xs font-semibold text-blue-700 hover:bg-blue-100"
                    title="Buka portal web resmi"
                  >
                    <ExternalLink className="h-3.5 w-3.5" />
                    Kunjungi
                  </a>
                )}
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Metode & Tarif Pajak</label>
              <select
                value={formData.metodePajak}
                onChange={(e) => {
                  const val = e.target.value as ProfilPerusahaan['metodePajak'];
                  let rate = 22;
                  if (val === 'UMKM_0.5') rate = 0.5;
                  setFormData({ ...formData, metodePajak: val, tarifPajakPersen: rate });
                }}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden bg-white"
              >
                <option value="BADAN_22">PPh Badan Normal (Tarif 22% dari Laba Kena Pajak)</option>
                <option value="UMKM_0.5">PPh Final PP 23 / 55 (Tarif 0.5% dari Omzet/Peredaran Bruto)</option>
                <option value="MANUAL">Kustom / Manual Percentage</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700">Tarif Pajak Efektif (%)</label>
              <input
                type="number"
                step="0.01"
                value={formData.tarifPajakPersen}
                onChange={(e) => setFormData({ ...formData, tarifPajakPersen: parseFloat(e.target.value) || 0 })}
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-xs font-medium focus:border-blue-500 focus:outline-hidden"
              />
            </div>
          </div>

          {/* Action buttons */}
          <div className="flex justify-end gap-3 pt-4 border-t border-slate-200">
            <button
              type="button"
              onClick={() => {
                stopCamera();
                onClose();
              }}
              className="rounded bg-slate-200 px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-300"
            >
              Batal
            </button>
            <button
              type="submit"
              className="inline-flex items-center gap-1.5 rounded bg-blue-600 px-5 py-2 text-xs font-semibold text-white shadow-xs hover:bg-blue-700"
            >
              <Check className="h-4 w-4" />
              Simpan Profil Perusahaan
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};
