'use client';

import { useMutation, useQuery } from '@tanstack/react-query';
import { Building2, Check, Loader2 } from 'lucide-react';
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  adminApi,
  type ProvisionAccountResult,
  type ProvisionDeveloperPayload,
} from '@/lib/admin-api';
import { ApiError } from '@/lib/api-client';
import {
  duAnApi,
  PROJECT_STATUS_LABELS,
  type ProjectSummary,
} from '@/lib/du-an-api';

/**
 * Admin → Provision a CĐT (DEVELOPER) account and link existing projects
 * whose `ownerId` is currently unassigned.
 */
export default function AdminProvisionDeveloperPage() {
  const [form, setForm] = React.useState<ProvisionDeveloperPayload>({
    phone: '',
    password: '',
    fullName: '',
    email: '',
    projectIds: [],
  });
  const [success, setSuccess] = React.useState<ProvisionAccountResult | null>(null);
  const [error, setError] = React.useState<string | null>(null);

  // List unassigned projects (status PLANNING or UNDER_CONSTRUCTION or any — admin
  // picks). We show all projects here; the backend rejects ones already owned.
  const { data: projectsResp } = useQuery({
    queryKey: ['admin-projects-all'],
    queryFn: () => duAnApi.search({ limit: 100 }),
    staleTime: 60_000,
  });

  const provision = useMutation({
    mutationFn: (payload: ProvisionDeveloperPayload) => adminApi.provisionDeveloper(payload),
    onSuccess: (res) => {
      setSuccess(res);
      setError(null);
      setForm({ phone: '', password: '', fullName: '', email: '', projectIds: [] });
    },
    onError: (err) => {
      setError(err instanceof ApiError ? err.message : 'Có lỗi xảy ra');
      setSuccess(null);
    },
  });

  const toggleProject = (id: string) => {
    setForm((f) => ({
      ...f,
      projectIds: f.projectIds?.includes(id)
        ? f.projectIds.filter((x) => x !== id)
        : [...(f.projectIds ?? []), id],
    }));
  };

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    provision.mutate({
      phone: form.phone.trim(),
      password: form.password,
      fullName: form.fullName.trim(),
      email: form.email?.trim() || undefined,
      projectIds: form.projectIds && form.projectIds.length > 0 ? form.projectIds : undefined,
    });
  };

  const projects: ProjectSummary[] = projectsResp?.data ?? [];

  return (
    <div className="mx-auto max-w-4xl space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Tạo tài khoản CĐT (Chủ đầu tư)</h1>
        <p className="text-sm text-muted-foreground">
          Cấp quyền truy cập dashboard cho một chủ đầu tư. Có thể gán ngay các dự án họ
          sở hữu (các dự án đã có CĐT khác sẽ bị từ chối).
        </p>
      </div>

      {success && (
        <div className="rounded-md border border-green-500/40 bg-green-500/10 p-4">
          <p className="flex items-start gap-2 text-sm text-green-700 dark:text-green-400">
            <Check className="mt-0.5 h-4 w-4 shrink-0" />
            <span>
              Đã tạo tài khoản <strong>{success.fullName}</strong> ({success.phone}).
              {success.linkedProjectIds && success.linkedProjectIds.length > 0 && (
                <> Gán cho {success.linkedProjectIds.length} dự án.</>
              )}
            </span>
          </p>
        </div>
      )}

      {error && (
        <div className="rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
          <button type="button" className="ml-2 underline" onClick={() => setError(null)}>
            Đóng
          </button>
        </div>
      )}

      <form onSubmit={onSubmit} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Thông tin tài khoản</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <Label htmlFor="fullName">Họ tên *</Label>
              <Input
                id="fullName"
                value={form.fullName}
                onChange={(e) => setForm({ ...form, fullName: e.target.value })}
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="phone">Số điện thoại *</Label>
              <Input
                id="phone"
                placeholder="+84912345678"
                value={form.phone}
                onChange={(e) => setForm({ ...form, phone: e.target.value })}
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="email">Email (tuỳ chọn)</Label>
              <Input
                id="email"
                type="email"
                value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="password">Mật khẩu tạm *</Label>
              <Input
                id="password"
                type="text"
                placeholder="Tối thiểu 8 ký tự"
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
                required
                minLength={8}
              />
              <p className="text-xs text-muted-foreground">
                CĐT đăng nhập lần đầu với mật khẩu này; khuyến nghị đổi sau khi nhận
                tài khoản.
              </p>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Gán dự án (tuỳ chọn)</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="mb-3 text-sm text-muted-foreground">
              Chọn các dự án sẽ giao cho CĐT này quản lý. Dự án đã có owner khác sẽ bị
              backend từ chối khi submit.
            </p>
            <div className="max-h-80 space-y-1 overflow-y-auto rounded-md border p-2">
              {projects.length === 0 && (
                <p className="text-sm text-muted-foreground">Chưa có dự án nào.</p>
              )}
              {projects.map((p) => {
                const checked = form.projectIds?.includes(p.id) ?? false;
                return (
                  <label
                    key={p.id}
                    className="flex cursor-pointer items-center gap-3 rounded-md px-2 py-2 hover:bg-accent"
                  >
                    <input
                      type="checkbox"
                      className="h-4 w-4"
                      checked={checked}
                      onChange={() => toggleProject(p.id)}
                    />
                    <Building2 className="h-4 w-4 text-primary" />
                    <div className="flex-1 min-w-0">
                      <p className="truncate text-sm font-medium">{p.name}</p>
                      <p className="truncate text-xs text-muted-foreground">
                        {p.developer.name} · {p.district}, {p.city}
                      </p>
                    </div>
                    <Badge variant="outline" className="text-xs">
                      {PROJECT_STATUS_LABELS[p.status]}
                    </Badge>
                  </label>
                );
              })}
            </div>
            {form.projectIds && form.projectIds.length > 0 && (
              <p className="mt-2 text-sm text-muted-foreground">
                Đã chọn <strong>{form.projectIds.length}</strong> dự án.
              </p>
            )}
          </CardContent>
        </Card>

        <div className="flex justify-end gap-3">
          <Button type="submit" disabled={provision.isPending}>
            {provision.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Tạo tài khoản CĐT
          </Button>
        </div>
      </form>
    </div>
  );
}
