import { Head, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/layouts/app-layout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

import { CrmSelect } from '@/components/crm-select';
interface Company {
  id: number;
  nama: string;
  kode_perusahaan: string;
  email: string | null;
  telepon: string | null;
  alamat: string | null;
  subscription_status: string;
  subscription_expires_at: string | null;
}

interface Props {
  company: Company;
  settings: Record<string, any>;
}

const steps = ['Perusahaan', 'Bisnis', 'Selesai'];

export default function Onboarding({ company, settings }: Props) {
  const [step, setStep] = useState(0);

  const companyForm = useForm({
    nama: company.nama ?? '',
    email: company.email ?? '',
    telepon: company.telepon ?? '',
    alamat: company.alamat ?? '',
  });

  const businessForm = useForm({
    business_type: settings.business_type ?? '',
    timezone: settings.timezone ?? 'Asia/Makassar',
    currency: settings.currency ?? 'IDR',
  });

  const saveCompany = () => {
    companyForm.put('/onboarding/company', {
      preserveScroll: true,
      onSuccess: () => setStep(1),
    });
  };

  const saveBusiness = () => {
    businessForm.put('/onboarding/business', {
      preserveScroll: true,
      onSuccess: () => setStep(2),
    });
  };

  const finish = () => router.post('/onboarding/finish');

  return (
    <AppLayout breadcrumbs={[{ title: 'Onboarding', href: '/onboarding' }]}>
      <Head title="Setup Perusahaan" />
      <div className="mx-auto w-full max-w-4xl space-y-6 p-4 md:p-8">
        <div>
          <h1 className="text-2xl font-semibold">Setup perusahaan</h1>
          <p className="text-muted-foreground">Lengkapi konfigurasi awal sebelum mulai menggunakan CRM.</p>
        </div>

        <div className="grid grid-cols-3 gap-2">
          {steps.map((label, index) => (
            <div key={label} className={`rounded-lg border p-3 text-center text-sm ${index === step ? 'border-primary bg-primary/5 font-medium' : ''}`}>
              <div className="mb-1 text-xs text-muted-foreground">Langkah {index + 1}</div>
              {label}
            </div>
          ))}
        </div>

        <Card>
          {step === 0 && (
            <>
              <CardHeader>
                <CardTitle>Profil perusahaan</CardTitle>
              </CardHeader>
              <CardContent className="space-y-5">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="nama">Nama perusahaan</Label>
                    <Input id="nama" value={companyForm.data.nama} onChange={(e) => companyForm.setData('nama', e.target.value)} />
                    {companyForm.errors.nama && <p className="text-sm text-destructive">{companyForm.errors.nama}</p>}
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email">Email perusahaan</Label>
                    <Input id="email" type="email" value={companyForm.data.email} onChange={(e) => companyForm.setData('email', e.target.value)} />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="telepon">Telepon</Label>
                    <Input id="telepon" value={companyForm.data.telepon} onChange={(e) => companyForm.setData('telepon', e.target.value)} />
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="alamat">Alamat</Label>
                    <Input id="alamat" value={companyForm.data.alamat} onChange={(e) => companyForm.setData('alamat', e.target.value)} />
                  </div>
                </div>
                <div className="flex justify-end">
                  <Button onClick={saveCompany} disabled={companyForm.processing}>Lanjut</Button>
                </div>
              </CardContent>
            </>
          )}

          {step === 1 && (
            <>
              <CardHeader>
                <CardTitle>Konfigurasi bisnis</CardTitle>
              </CardHeader>
              <CardContent className="space-y-5">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="business_type">Jenis bisnis</Label>
                    <Input id="business_type" placeholder="Contoh: Distribusi FMCG" value={businessForm.data.business_type} onChange={(e) => businessForm.setData('business_type', e.target.value)} />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="timezone">Timezone</Label>
                    <CrmSelect id="timezone" className="border-input bg-background w-full rounded-md border px-3 py-2 text-sm" value={businessForm.data.timezone} onChange={(e) => businessForm.setData('timezone', e.target.value)}>
                      <option value="Asia/Makassar">Asia/Makassar (WITA)</option>
                      <option value="Asia/Jakarta">Asia/Jakarta (WIB)</option>
                      <option value="Asia/Jayapura">Asia/Jayapura (WIT)</option>
                    </CrmSelect>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="currency">Mata uang</Label>
                    <Input id="currency" maxLength={3} value={businessForm.data.currency} onChange={(e) => businessForm.setData('currency', e.target.value.toUpperCase())} />
                  </div>
                </div>
                <div className="flex justify-between">
                  <Button variant="outline" onClick={() => setStep(0)}>Kembali</Button>
                  <Button onClick={saveBusiness} disabled={businessForm.processing}>Lanjut</Button>
                </div>
              </CardContent>
            </>
          )}

          {step === 2 && (
            <>
              <CardHeader>
                <CardTitle>Siap digunakan</CardTitle>
              </CardHeader>
              <CardContent className="space-y-5">
                <div className="rounded-lg bg-muted p-4 text-sm">
                  <div className="font-medium">{companyForm.data.nama}</div>
                  <div className="text-muted-foreground">Kode perusahaan: {company.kode_perusahaan}</div>
                  <div className="mt-2">Paket: <strong>{company.subscription_status}</strong></div>
                  {company.subscription_expires_at && <div>Trial berakhir: <strong>{company.subscription_expires_at}</strong></div>}
                </div>
                <p className="text-sm text-muted-foreground">Anda sudah siap masuk ke dashboard. Data customer, produk, sales, order, invoice, dan laporan dapat mulai diisi dari menu CRM.</p>
                <div className="flex justify-between">
                  <Button variant="outline" onClick={() => setStep(1)}>Kembali</Button>
                  <Button onClick={finish}>Masuk Dashboard</Button>
                </div>
              </CardContent>
            </>
          )}
        </Card>
      </div>
    </AppLayout>
  );
}
